-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 10 posts ] 
Author Message
 Post subject: ORDER BY named parameter in Named Queries (Dynamic ORDER BY)
PostPosted: Fri Aug 11, 2006 5:41 pm 
Beginner
Beginner

Joined: Thu May 06, 2004 4:06 pm
Posts: 25
I am using externalized named queries (named queries in my mapping document). After reading through the forums, is it safe to assume I can NOT use a named parameter for the ORDER BY clause?

Code:
<query name="..">
    FROM eg.Something ORDER BY ?
</query>

..as setting the named parameter has no effect on the order of the results.

So, if this cannot be done... what is the best way to dynamically define the ORDER BY named parameter? I would like to use externalized named queries, if possible. Any suggestions? or do i have to revert back internalized named queries?

Thanks

Hibernate version: 3.1.3, 3.1.2CR2

Mapping documents:

Code:
<query name="eg.DomesticCat.by.name.and.minimum.weight"><![CDATA[
    FROM eg.DomesticCat AS cat
        ORDER BY :orderby
] ]></query>


Code between sessionFactory.openSession() and session.close():

Query q = sess.getNamedQuery("eg.DomesticCat.by.name.and.minimum.weight");
q.setString( "orderby", "cat.name" );
List cats = q.list();

Name and version of the database you are using:

MySQL 5.0.21

The generated SQL (show_sql=true):

.... ORDER BY ?


Top
 Profile  
 
 Post subject: Problem with order by clause with named parameter.
PostPosted: Mon Oct 02, 2006 6:10 am 
Newbie

Joined: Mon Oct 02, 2006 5:53 am
Posts: 2
Location: Paris, France
Hi,
i'm trying to achieve the same thing, i.e using a named parameter to dynamically create an order by clause. However i'm not using a named query but a standard HQL query built in the code.
Code:
EntityManager em=getEntityManager();
StringBuffer queryString=new StringBuffer("select s from mytable s where s.user=:user order by :order asc");
query=em.createQuery(queryString.toString());
query.setFirstResult(first);
query.setMaxResults(pageSz);
query.setParameter("user", getUser());
query.setParameter("order", sortColumnName);
List l=query.getResultList();


The result does not take the ordering constraint into account.
I've turned on logging on the MySQL server and i see that the query is being run as the following:

Code:
select s0_.Id as Id4_, s0_.user as user4, s0_.mobile as mobile2_4_, s0_.displayname as displayn3_4_ from p.mytable s0_ where s0_.user=1 order by 'Displayname' asc limit 3;


I see that the sort column name is being included in quotes, which makes the order by ineffective. Quotes should not be added to the column name.
Has someone seen this behaviour ? I cannot find a way to get those quotes removed :(
I'm running Hibernate 3.2 with Hibernate Annotations and Hibernate EntityManager 3.2.0 CR2. My database is MYSQL 5.0.22.

Any help would be appreciated !
Thanks in advance.

_________________
Charles-Edouard Ruault


Top
 Profile  
 
 Post subject:
PostPosted: Tue Oct 03, 2006 8:32 pm 
Regular
Regular

Joined: Thu Jul 01, 2004 12:13 am
Posts: 68
Location: San Diego, CA
I'm seeing the same issue with HB 3.1.2. If I use a dynamic sort with regular HQL, I see what you're seeing. If I hard code the sort value, it works fine. Looking into the Hibernate code and will get back later...

Lou


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 04, 2006 3:57 am 
Newbie

Joined: Mon Oct 02, 2006 5:53 am
Posts: 2
Location: Paris, France
I think i figured it out. It's because Hibernate uses a PreparedStatement and the column name is a parameter to the PreparedStatement. This goes against the PreparedStatement spirit. I found out this thread http://forum.java.sun.com/thread.jspa?threadID=478053&messageID=2223214
That discusses the topic. I've changed my code so that the order by column name is not a Parameter to the HQL query anymore and everything is now fine.

_________________
Charles-Edouard Ruault


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 04, 2006 2:11 pm 
Regular
Regular

Joined: Thu Jul 01, 2004 12:13 am
Posts: 68
Location: San Diego, CA
charlus wrote:
I've changed my code so that the order by column name is not a Parameter to the HQL query anymore and everything is now fine.


I came to the same conclusion after switch my hard-coded value to a parametric value and building with a StringBuffer like this:

Code:
                StringBuffer sb = new StringBuffer(255);
                sb.append(queryString).append(
                        DBServiceConstants.CONST_ORDER_BY)
                        .append(orderByParam).append(
                                (isAscending ? DBServiceConstants.CONST_ASC
                                        : DBServiceConstants.CONST_DESC));
                Query query = session.createQuery(sb.toString());


Best,
Lou


Top
 Profile  
 
 Post subject:
PostPosted: Tue Dec 05, 2006 7:56 am 
Beginner
Beginner

Joined: Wed Apr 26, 2006 4:40 am
Posts: 24
[EDIT] OOps double post :P


Last edited by Thomson on Wed Dec 06, 2006 6:35 am, edited 1 time in total.

Top
 Profile  
 
 Post subject:
PostPosted: Tue Dec 05, 2006 8:18 am 
Beginner
Beginner

Joined: Wed Apr 26, 2006 4:40 am
Posts: 24
charlus wrote:
I think i figured it out. It's because Hibernate uses a PreparedStatement and the column name is a parameter to the PreparedStatement. This goes against the PreparedStatement spirit. I found out this thread http://forum.java.sun.com/thread.jspa?threadID=478053&messageID=2223214
That discusses the topic. I've changed my code so that the order by column name is not a Parameter to the HQL query anymore and everything is now fine.


The problem is that applications become horrendously complicated without that feature.

A simple example is a table where the data can be sorted by each column, ascending and descending. There are 10 columns. This results in a whopping 20 queries. Than you can filter the table by 5 different criteria -> 100 queries.

You have either the option to code this as a criteria query, which is simply far to cumbersome for some queries, or build your HQL using String concatenation, which is not far better then creating plain SQL in your code.


Top
 Profile  
 
 Post subject: Re: ORDER BY named parameter in Named Queries (Dynamic ORDER BY)
PostPosted: Mon Jun 18, 2012 6:50 am 
Newbie

Joined: Mon Jun 18, 2012 6:00 am
Posts: 2
Hi Charles,
Am facing the same problem, setting a dynamic order by clause for hibernate. I tried going to the link u have provided. but it does not seem to exist anymore. Can u please tell me how did u solve the issue as i cannot append order by string dynamically into the query as it would reflect as a SQL injection issue in the security scan.


Top
 Profile  
 
 Post subject: Re: ORDER BY named parameter in Named Queries (Dynamic ORDER BY)
PostPosted: Mon Jun 18, 2012 6:51 am 
Newbie

Joined: Mon Jun 18, 2012 6:00 am
Posts: 2
If anyone else has a work around for this please do share your solution for this problem. Would appreciate it :)


Top
 Profile  
 
 Post subject: Re: ORDER BY named parameter in Named Queries (Dynamic ORDER BY)
PostPosted: Thu Mar 14, 2013 2:08 pm 
Newbie

Joined: Tue Sep 18, 2012 12:00 am
Posts: 6
If you are using JPA1 you can use below function or You can use unwrap method from JPA2


public static String unWrapNamedQuery(javax.persistence.Query query){

String sqlString="";
String queryObject=ToStringBuilder.reflectionToString(query, ToStringStyle.SIMPLE_STYLE);
String pattern = "(?i)(SELECT)(.+?)(ORDER)(\\s+)(BY)";
java.util.regex.Matcher matcher = Pattern.compile(pattern).matcher(queryObject);
if (matcher.find()) {
sqlString=matcher.group();
}

return sqlString;
}


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 10 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.