Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a named query as below;

@NamedQuery(name = "MyEntityClass.findSomething", query = "SELECT item FROM MyTable mytbl")

Now I want to append dynamic sort clause to this query (based on UI parameters)

Can I get an example using JPQL for doing the same (like how to set a dynamic ORDER BY in the Entity class)

I have already tried using CriteriaQuery, but was looking for a JPQL implementation now.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

NamedQueries are by definition NOT dynamic, it is not correct to change them programmatically.

So the way to go is to create a JPQL query (but not a named query) like this:

TypedQuery<MyEntity> query = em.createdQuery("SELECT item FROM MyEntity item ORDER BY "+sortingCol, MyEntity.class);

On the other hand, if you REALLY want to use the named query, you could do that the following way:

@NamedQuery(name = "MyEntityClass.findSomething", query = MyEntity.NAMED_QUERY)
@Entity
public class MyEntity {
    public static final NAMED_QUERY= "SELECT item FROM MyTable mytbl";
    //+your persistent fields/properties...
}
//and later in your code
TypedQuery<MyEntity> query = entityManager.createQuery(MyEntity.NAMED_QUERY + " ORDER BY " + sortingCol, MyEntity.class);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...