Tuesday, December 17, 2013

Get JPQL String From a NamedQuery in JPA

So, currently I'm working with 'pure' JPA, try to not to import any specific implementation to my Java project(s). Then, I has this problem. I have a query in NamedQuery JPA, called to fill a datatable in the UI.
The datatable itself using Primefaces, with sorting capability. I already built the sorting function, but the problem is: I need the JPQL to select which column to be sorted, not based on NamedQuery.

String queryString = getEntityManager().createNamedQuery(queryName).doSomethingHere() ///??
setSortOrderInfoForQuery(queryString); // sorting here
Query queryObject = getEntityManager().createQuery(queryString);

But I later I found out that no single implementation, every implementation have different function. It's explained very clear in Antonio Goncalves blog.

For the reason of efficiency (and backup) I'm copied here, what Antonio's conclusion in his blog (all credits to him):

Conclusion

As you can see, it’s not that simple to get a String representation for a TypedQuery. Here is a digest of the three main ORMs :
ORM FrameworkQuery implementationHow to get the JPQL StringHow to get the SPQL String
EclipseLinkJpaQuerygetDatabaseQuery().getJPQLString()*getDatabaseQuery().getSQLString()**
HibernateQueryN/AgetQueryString()
OpenJPAQueryImplgetQueryString()N/A
(*) Only possible on a dynamic or named query. Not possible on a CriteriaQuery
(**) You need to execute the query first, if not, the value is null
To illustrate all that I’ve written simple test cases using EclipseLinkHibernate and OpenJPA that you can download from GitHub. Give it a try and let me know.

And what about having an API in JPA 2.1 ?

For a developers’ point of view it would be great to have two methods in the javax.persistence.Query (and therefore javax.persistence.TypedQuery) interface that would be able to easily return the JPQL and SQL String representations, e.g : Query.getJPQLString() and Query.getSQLString(). Hey, that would be the perfect time to have it in JPA 2.1 that will be shipped in less than a year. Now, as an implementer, this might be tricky to do, I would love to ear your point of view on this.
Anyway, I’m going to post an email to the JPA 2.1 Expert Group… just in case we can have this in the next version of JPA ;o)


And since his article is from 24/05/2012, I think the standard API (function) is still not implemented :(

Update: And what's the workaround? Don't use named query, as simple as that.

No comments:

Post a Comment