JPA criteria query in a many-to-many relationship using IN operator

馋奶兔 提交于 2019-12-11 03:13:38

问题


I have the following two entities:

Profile, Category

In the Profile entity i have a List of categories that the profile has

In the Category entity i have a List of profiles that the category has

The generated table is called profiles_has_categories and has the following columns:

profile_id, category_id

I want to find all profiles that belong to any of the categories with the following ids 1, 2, 3, 4

I would do that in plain sql with:

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

But i can't figure out how to do that using the CriteriaBuilder to construct a query in 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:


You don't want a get, you want a join:

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


来源:https://stackoverflow.com/questions/31125443/jpa-criteria-query-in-a-many-to-many-relationship-using-in-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!