Reputation: 173
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
Upvotes: 1
Views: 3119
Reputation: 10716
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.
Upvotes: 0
Reputation: 173
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.
Upvotes: 1