JPA2 +休眠+订购方式

发布于 2024-09-04 12:26:38 字数 803 浏览 2 评论 0原文

是否可能(使用 Hibernate 和 JPA2 Criteria Builder) 按方法结果而不是实体成员排序?

public class X {
    protected X() {}
    public String member;
    public String getEvaluatedValue() { // order by
        return "a status calculated with various members";
    }
}

我想要实现的是按 getEvaluatedValue() 的结果排序。这可能吗?

我没有使用@Formular,但

EntityManager em = ...;
QueryBuilder builder = em.getQueryBuilder();
SomeQueryClass query = builder.createQuery(MyTargetClass.class);
query.orderBy(builder.asc(... some code...));

我虽然它是普通的JPA2,当然你是对的,没有机会按动态数据排序。但是我可能被允许使用 if-else 或任何语句(用我的 QueryBuilder 定义)指定一些 order-by 块,不是吗?

Is it possible (using Hibernate and JPA2 Criteria Builder) to order by a methods result rather than an entities member?

public class X {
    protected X() {}
    public String member;
    public String getEvaluatedValue() { // order by
        return "a status calculated with various members";
    }
}

What I want to achieve is order by the result of getEvaluatedValue(). Is that possible?

I'm not using @Formular, but

EntityManager em = ...;
QueryBuilder builder = em.getQueryBuilder();
SomeQueryClass query = builder.createQuery(MyTargetClass.class);
query.orderBy(builder.asc(... some code...));

I though it is plain JPA2 and certainly you are right there is no chance to order by dynamic data. But I may be allowed to specify some order-by block with an if-else or whatever statement (defined with my QueryBuilder), won't I?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

人间不值得 2024-09-11 12:26:38

我不知道这是否可能(如果一个属性是瞬态的,即在数据库中没有表示,那么 SQL 结果应该是什么?)但是,更重要的是,按 "some 排序之间有什么区别?测试“+成员成员?也许这只是一个例子......

I don't know if it is possible (if an attribute is transient i.e. doesn't have a representation in database, what should be the SQL result?) but, more important, what would the difference between ordering by "some test " + member and member? Maybe that's just an example though...

鹿港小镇 2024-09-11 12:26:38

看起来这是不可能的,原因如下:
当在SQL层运行查询时,不会计算“EvaluatedValue”字段。它仅在稍后填充(具体时间,我不知道,这可能取决于实体是否使用 LAZY 模式)。
JPA 查询对象与 SQL(即数据库中的内容)紧密相关。

也许,我会使用 getResultList() 获得未排序的结果,然后手动对它们进行排序:

使您的 EvaluatedValue 成为实现 Comparable 的类型:
参见此处

Looks like it cannot be possible, for this reason :
when the query is run in the SQL layer, the "EvaluatedValue" field is not calculated. It is only populated later (when exactly, I dont know, it may depend on if the entity uses a LAZY mode or not).
The JPA Query object is closely tied to SQL, ie what is in the database.

Probably, I would get the non sorted results with a getResultList(), then manually sort them :

making your EvaluatedValue a type that implements Comparable :
see here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文