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

Mic*_*kis 2 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)
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何使用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();
Run Code Online (Sandbox Code Playgroud)

Tob*_*fke 10

你不想得到,你想要一个加入:

criteria.where(root.join(Profile_.categories).in(categories))
Run Code Online (Sandbox Code Playgroud)