JPA条件使用IN运算符以多对多关系查询

时间:2015-06-29 20:58:17

标签: java sql hibernate jpa hibernate-criteria

我有以下两个实体:

个人资料,类别​​

在配置文件实体中,我有一个配置文件具有的类别列表

在类别实体中,我有一个类别列表

生成的表名为 profiles_has_categories ,并包含以下列:

profile_id,category_id

我想找到属于任何类别的所有配置文件,其中包含以下ID 1,2,3,4

我会在普通的sql中使用:

SELECT p.* FROM profiles p, profiles_has_categories phc 
WHERE p.id = phc.profile_id 
AND phc.category_id IN (1, 2, 3, 4)

但我无法弄清楚如何使用CriteriaBuilder在JPA中构建查询:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Profile> criteria = cb.createQuery(Profile.class);
Root<Profile> root = criteria.from(Profile.class);

// Profile_.categories is a collection of Category objects
// categories is collection of Long (category ids) that i want to search in
// but is not working
criteria.where(root.get(Profile_.categories).in(categories))

List<Profile> results = em.createQuery(criteria).getResultList();

1 个答案:

答案 0 :(得分:8)

您不希望获取,您想要加入

criteria.where(root.join(Profile_.categories).in(categories))
相关问题