我有以下两个实体:
简介、类别
在配置文件实体中,我有一个配置文件具有的类别列表
在类别实体中,我有一个类别具有的配置文件列表
生成的表名为 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();
最佳答案
你不需要get,你想要join:
criteria.where(root.join(Profile_.categories).in(categories))
关于java - 使用 IN 运算符在多对多关系中进行 JPA 条件查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31125443/