using subqueries in jpa criteria api

后端 未结 2 1516
北荒
北荒 2020-12-20 07:54

I\'m studying JPA criteria api and my database contains Employee table. I am trying to find all the employees who are paid second highest salary. I was able to write JPQL su

2条回答
  •  粉色の甜心
    2020-12-20 08:39

    As documented, it cannot work because Number is not Comparable:

    > Predicate lessThan(Expression x,
                                                                   Expression y)
    

    For expression with Number there is method Criteriabuilder.lt that takes such arguments:

    c.where(cb.lt(e2.get("salary"), e3.get("salary")));
    

    Other option is to change type argument from Number to something more specific. If salary is Long, following should work:

    Subquery sq = c.subquery(Long.class);
    Root e2 = sq.from(Employee.class);
    sq.select(cb.max(e2. get("salary")));
    
    Subquery sq1 = sq.subquery(Long.class);
    Root e3 = sq1.from(Employee.class);
    sq1.select(cb.max(e3. get("salary")));
    
    c.where(cb.lessThan(e2.get("salary"), e3.get("salary")));
    c.where(cb.equal(e1.get("salary"), sq));
    

提交回复
热议问题