简体   繁体   中英

JPA Criteria Query Builder: Get last Entry

I am currently building a complex query with JPA CriteriaBuilder.
In this query i join a little databases. Now i need only the last Entry of a joined Table. But i don't know where i must applicate that in the query.

Here is a dummy JPA query:

private CriteriaQuery<Class2> getClass2Function {
    CriteriaQuery<RootClass> cq = cb.createQuery(RootClass.class);
    Root<RootClass> root = cq.from(RootClass.class);
    Join<RootClass, Class2> class2 = root.join(RootClass_.class2Id);
    ListJoin<Class2, Class3> class3 = class2.join(Class2_.listOfClass3);

    List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.isNull(class3.get(SomeModel_.dtDl)));
    predicates.add(cb.isNull(class2.get(SomeModel_.dtDl)));
    predicates.add(cb.isNull(root.get(SomeModel_.dtDl)));

    return cq.select(class2).where(predicates.toArray(new Predicate[] {}))
              .orderBy(cb.asc(class2.get(Class2_.id)));
}

Now i need only the last entry of the ListJoin class3 , how can i do this?

Greetings

I have found a solution.
I needed to add the following code:

Subquery<Long> sq = cq.subquery(Long.class);
Root<Class3> root = sq.from(Class3.class);
sq.select(cb.max(root.get(Class3_.id)));
predicates.add(cb.equal(class3.get(Class3_.id), sq));

I hope i could help someone.

First of all, if you care about the order of elements in a list, you need the @OrderColumn annotation. Depending on any other mechanism for maintaining list order is dependent on the database and persistence provider and, in the general case, unreliable.

Assuming you already have that, you should be able to combine class3.order() with cb.size(class3) in a predicate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM