JPA 2 Criteria - using “in” and subqueries(?)

自作多情 提交于 2020-01-05 07:27:38

问题


I have a trouble with creating JPA 2 query (actually I'm using Spring Data JPA). I have a 2 tables:
- Users (id,company_id,name,surname,status)
- UsersGroup (id,user_id,group_id).
Users can(and often are) connected to more than one group.

What I'm trying to do is to get distinct list of users according to filtering options from search form (name,surname,status) and attributes taken from logged user (company_id, group_id), because I want to show this user only users within company and group he also belongs to.

I'm using Specification/Predicate/Criteria from JPA 2 and Spring Data to do this, and I wrote this code:

public static Specification<User> filteredList(final ListFilterBean searchFilter, final LoggedUserBean loggedUser) {
    return new Specification<User>() {

        @Override
        public Predicate toPredicate(Root<User> root,
                CriteriaQuery<?> query, CriteriaBuilder cb) {

            List<Predicate> predicates = new ArrayList<Predicate>();

            root.join("userGroups");

            predicates.add(cb.equal(root.<Long>get(User_.companyId), loggedUser.getCompanyId()));
            predicates.add(cb.like(cb.upper(root.<String>get(User_.name)), getLikePattern(searchFilter.getName())));
            predicates.add(cb.like(cb.upper(root.<String>get(User_.surname)), getLikePattern(searchFilter.getSurname())));
            predicates.add(cb.equal(cb.upper(root.<String>get(User_.status)), searchFilter.getStatusId().charAt(0)));

            query.distinct(true);

            return cb.and(predicates.toArray(new Predicate[0]));
        }
    };
}

Which produces SQL below:

select
    * 
from
    ( select
        distinct user0_.id as id5_,
        user0_.name as name5_,
        user0_.surname as surname5_
    from
        users user0_ 
    inner join
        user_group usergroup1_ 
            on user0_.id=usergroup1_.user_id 
    where
        user0_.company_id=1

and ( user0_.id in (select distinct user_id from user_group where user_group.group_id in (1, 2, 3)) )

        and (
            upper(user0_.name) like '%'
        ) 
        and (
            upper(user0_.surname) like '%'
        ) 
        and upper(user0_.status)='A' ) 
where
    rownum <= 15

Bolded part of code is the part doesn't actually exist and this is my main question. How to write expression (Predicate) to incorporate this part of SQL into query?

Thanks in advance :)

来源:https://stackoverflow.com/questions/13460235/jpa-2-criteria-using-in-and-subqueries

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