【发布时间】:2015-09-16 11:49:27
【问题描述】:
我有以下两个实体:
个人资料、类别
在个人资料实体中,我有一个个人资料具有的类别列表
在类别实体中,我有一个类别具有的配置文件列表
生成的表名为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();
【问题讨论】:
标签: java sql hibernate jpa hibernate-criteria