问题描述
我有一个命名查询如下;
I have a named query as below;
@NamedQuery(name = "MyEntityClass.findSomething", query = "SELECT item FROM MyTable mytbl")
现在我想在此查询中附加动态排序子句(基于UI)参数)
Now I want to append dynamic sort clause to this query (based on UI parameters)
我可以使用JPQL做一个相同的例子(比如如何在Entity类中设置动态ORDER BY)
Can I get an example using JPQL for doing the same (like how to set a dynamic ORDER BY in the Entity class)
我已经尝试过使用CriteriaQuery,但现在正在寻找JPQL实现。
I have already tried using CriteriaQuery, but was looking for a JPQL implementation now.
推荐答案
NamedQueries是根据定义,不是动态的,以编程方式更改它们是不正确的。
NamedQueries are by definition NOT dynamic, it is not correct to change them programmatically.
所以要做的就是创建一个JPQL查询(但不是命名查询),如下所示:
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);
这篇关于使用JPQL示例的Entity类中的动态命名查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!