views:

300

answers:

2

Hi.

Is it possible (using Hibernate and JPA2 Criteria Builder [1]) to order by a method's result rather than an entity's 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 achive is order by the result of getEvaluatedValue(). Is that possible?

Thanks in advanced.

EDIT: Added reply.

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?

[1] http://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html_single/#querycriteria

A: 

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
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
@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
see initial post for reply
Jan
A: 

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