Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get query string from a javax.persistence.Query?

Maybe I am missing something, but I simply want to (in my java program) get the query string from a javax.persistence.Query object? The Query object itself doesn't seem to have a method to do that. Also I know that our manager doesn't want us to use Spring framework stuff (for example using their QueryUtils class).

Is there not a way to simply get the query string from javax.persistence.Query object (Again, in a java program) ?!

like image 738
user1006375 Avatar asked Nov 28 '12 16:11

user1006375


People also ask

How do I print query criteria?

Open the query. Select File, Print Preview from the menu bar. The Query Control Report will appear.

What is setParameter query?

The Query. setParameter(integer position, Object value) method is used to set the parameter values. Input parameters are numbered starting from 1.

What is createNativeQuery in JPA?

Create ad-hoc native queries Creating an ad-hoc native query is quite simple. The EntityManager interface provides the createNativeQuery method for it. It returns an implementation of the Query interface, which is the same that you get when you call the createQuery method to create a JPQL query.

What is typed query in JPA?

But, JPA provides a special Query sub-type known as a TypedQuery. This is always preferred if we know our Query result type beforehand. Additionally, it makes our code much more reliable and easier to test. This way, we get stronger typing for free, avoiding possible casting exceptions down the road.


3 Answers

no problem. hibernate:

query.unwrap(org.hibernate.Query.class).getQueryString()

or eclipselink

query.unwrap(JpaQuery.class).getDatabaseQuery().getJPQLString(); // doesn't work for CriteriaQuery query.unwrap(JpaQuery.class).getDatabaseQuery().getSQLString();

or open JPA

query.unwrap(org.apache.openjpa.persistence.QueryImpl.class).getQueryString()

...you get the idea....

like image 81
tom Avatar answered Nov 11 '22 23:11

tom


There is no JPA-standard way, but some implementations have their own methods. For example DataNucleus JPA allows you to do

query.toString();

Look at the docs of your implementation for how they do it. See also this blog entry http://antoniogoncalves.org/2012/05/24/how-to-get-the-jpqlsql-string-from-a-criteriaquery-in-jpa/

like image 41
DataNucleus Avatar answered Nov 12 '22 01:11

DataNucleus


There is no standard way in JPA,

If you are using EclipseLink see,

http://wiki.eclipse.org/EclipseLink/FAQ/JPA#How_to_get_the_SQL_for_a_Query.3F

like image 24
James Avatar answered Nov 11 '22 23:11

James