1

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?

Draken
  • 3,134
  • 13
  • 34
  • 54
Jan
  • 1,594
  • 1
  • 20
  • 30

2 Answers2

0

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...

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • It's of course just an example. The problem is that I have to calculate an event status, which depends on various members. Because it is calculated it does not make sense to store it in the database just for sorting purpose. – Jan Jun 07 '10 at 21:50
  • 1
    @Jan Yes, I agree. But I don't think that the database would do a good job at sorting the result anyway (because of the lack of index). I'll dig this a bit more since my understanding is that you are using a `@Formula` and not plain standard JPA2.0 (so there is maybe an Hibernate way). – Pascal Thivent Jun 07 '10 at 23:39
0

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

spiritoo
  • 451
  • 5
  • 15