JPA @ElementCollection如何查询?

Yon*_*kee 13 java sql hibernate jpa spring-data

我正在使用Spring JPA,为了向我的实体添加一个String列表,我正在使用@ElementCollection,如下所示.

@ElementCollection
private Map<Integer, String> categories;
Run Code Online (Sandbox Code Playgroud)

当我使用它时,它会生成一个名为subscription_categoriesthis 的表,其中包含以下列subscription(varchar), catergories(varchar) and caterogies_key (int)

如果我在桌面上使用我的SQL工具,我可以使用以下内容查询此表

select `subscription_categories`.`subscription` from `subscription_categories` where `subscription_categories`.`categories`='TESTING';
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试在Spring Data中使用它时,它会因"... not mapped"错误而失败

以下是一些尝试:

@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);
Run Code Online (Sandbox Code Playgroud)

两者都返回相同的错误.

引起:org.hibernate.hql.internal.ast.QuerySyntaxException:未映射类别

我的问题是:

如何查询@ElementCollection创建的表?

小智 6

在这一点上我也支持@talex,并认为您需要将查询基于@ElementCollection 的父/容器/基础对象。

根据我的经验,以下查询应该足够了:

@Query("select category from Subscription subscription inner join subscription.categories category")

旁注:查询 subscription_categories 似乎是错误的路径,因为该表是不同层(Sql/Jpql 中的数据库层)的一部分,而查询应该在 Hibernate 层(hql)上形成,它使用您的实体/类名作为参考。我使用大写的类名,而不是小写的表名。


tal*_*lex 5

您不能直接从查询@ElementCollection。您应该查询基本实体(我假设其名称为Subscroption)。

@Query("select s from Subscroption s where s.categories = ?1")
List<Subscription> findUsernameByCategory(String category);
Run Code Online (Sandbox Code Playgroud)

如果要按键查询,请使用

@Query("select s from Subscroption s where index(s.categories) = ?1")
List<Subscription> findUsernameByCategoryKey(Integer key);
Run Code Online (Sandbox Code Playgroud)