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 getEvaluatedValu开发者_高级运维e()
. 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?
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...
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
精彩评论