我正在使用 Spring JPA,为了向我的实体添加一个字符串列表,我正在使用 @ElementCollection,如下所示。
@ElementCollection
private Map<Integer, String> categories;
当我使用它时,它会生成一个名为 subscription_categories
的表,其中包含以下列 subscription(varchar)、catergories(varchar) 和 caterogies_key (int)
如果我在桌面上使用我的 SQL 工具,我可以使用以下命令很好地查询此表
select `subscription_categories`.`subscription` from `subscription_categories` where `subscription_categories`.`categories`='TESTING';
但是,当我尝试在 Spring Data 中使用它时,它失败并显示“...未映射”错误
下面是一些尝试:
@Query("select s.subscription from subscription_categories s where s.categories = ?1")
List<Subscription> findUsernameByCategory(String category);
@Query("select s.subscription from categories s where s.categories = ?1")
List<Subscription> findUsernameByCategory(String category);
两者都返回相同的错误。
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: categories is not mapped
我的问题是:
如何查询由@ElementCollection 创建的表?
最佳答案
您不能直接从@ElementCollection
查询。您应该查询基本实体(我假设它的名称是 Subscription
)。
@Query("select s from Subscription s where s.categories = ?1")
List<Subscription> findUsernameByCategory(String category);
如果要按键查询,则使用
@Query("select s from Subscription s where index(s.categories) = ?1")
List<Subscription> findUsernameByCategoryKey(Integer key);
关于java - JPA @ElementCollection 如何查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41528167/