简体   繁体   English

JPA条件查询构建器:获取最后一个条目

[英]JPA Criteria Query Builder: Get last Entry

I am currently building a complex query with JPA CriteriaBuilder. 我目前正在使用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: 这是一个虚拟的JPA查询:

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? 现在我只需要ListJoin class3的最后一个条目,我该怎么做?

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. 首先,如果您关心列表中元素的顺序,则需要@OrderColumn批注。 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. 假设您已经拥有了,那么您应该能够在谓词class3.order()cb.size(class3)组合在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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