【问题标题】:JPA criteria query in a many-to-many relationship using IN operator使用 IN 运算符以多对多关系查询 JPA 条件
【发布时间】: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


    【解决方案1】:

    你不想要一个get,你想要一个join

    criteria.where(root.join(Profile_.categories).in(categories))
    

    【讨论】:

    • 谢谢!这就是我一直在寻找的。​​span>
    猜你喜欢
    • 2013-11-18
    • 2011-02-27
    • 2021-10-25
    • 1970-01-01
    • 2014-04-08
    • 2021-11-20
    • 1970-01-01
    • 2015-12-23
    • 2011-09-21
    相关资源
    最近更新 更多