开发者

More elegant way to write a hibernate query

开发者 https://www.devze.com 2023-03-03 06:25 出处:网络
Can someone help me write a better code. I tried this but its not working : Query query = session.createQuery(\"from MyTable order by :sortvariable :sortorder\");

Can someone help me write a better code. I tried this but its not working :

Query query = session.createQuery("from MyTable order by :sortvariable :sortorder");
query.setParameter("sortvariable", sortvar);
query.setParameter("sortorder", order);

This is not working as well

开发者_Go百科
Query query = session.createQuery("from MyTable table order by table." + sortvar + " " + " :sortorder");
query.setParameter("sortorder", order);

I managet to get it working with this :

Query query = session.createQuery("from MyTable table order by table." + sortvar + " " + order);

I need to do this with query because I'm using setMaxResults() and setFirstResult().


I don't think you can use parameters to identify keywords that way. Is it possible to do what you're trying to do using the criteria API?

boolean sortAscending = ...;
Criteria criteria = session.createCriteria(MyTable.class);
criteria.addOrder(sortAscending? Order.asc(sortVar): Order.desc(sortVar));
0

精彩评论

暂无评论...
验证码 换一张
取 消