views:

317

answers:

3

Is it possible to access the SQL which is generated by JPQL?

I would like to use the SQL to later create a view for my purposes.

I am using Hibernate if it matters.

+1  A: 

You can set the hibernate.show_sql property to true, then all the SQL will be shown on the console.

<property name="hibernate.show_sql">true</property>
beny23
Thanks, but i need the SQL accessible in my application programmatically.
JavaRocky
+1  A: 

So you need to write your own JPQL implementation then :-) After all, converting JPQL into SQL for an RDBMS datastore is what a JPQL implementation is. Good Luck!

Sure you could make use of an existing JPQL implementation though, whether Hibernate, or EclipseLink, or DataNucleus ... and since they are all open source you ought to go and dig in their codebase.

DataNucleus
Thanks DN. *sigh* haha.
JavaRocky
A: 

Is it possible to access the SQL which is generated by JPQL?

You can access the SQL String from an Hibernate Interceptor, more precisely from the method Interceptor.html#onPrepareStatement(java.lang.String)

onPrepareStatement

String onPrepareStatement(String sql) Called when sql string is being prepared. Parameters: sql - sql to be prepared Returns: original or modified sql

If you decide to go this way, the best option is to extends EmptyInterceptor and to override only the methods you want.

You can hook your interceptor using the following declaration in your persistence.xml:

<properties>
  <property name="hibernate.ejb.interceptor" value="com.acme.MyInterceptor"/>
</properties>
Pascal Thivent