0

Is there a way to get the SQL query from a session.get(class name, id) call? I saw this post earlier: How to get SQL from Hibernate Criteria API (*not* for logging) but it does not cover get queries.

Clarification: I am looking for an API method to get the query string, not from the query log. In other words I am asking if there is a method (like toSql below) where instead of:

Foo foo = session.get(Foo.class, id);

I can say something like:

String sqlOrHql = session.get(Foo.class, id).toSql();
// execute sqlOrHql to get foo, either through hibernate or manually using JDBC
Community
  • 1
  • 1
JRR
  • 6,014
  • 6
  • 39
  • 59
  • Note that it should be more complicated than getting SQL from criteria query for the following reasons: 1)If your entity has relationships with other entities, then get(clazz,id) could execute more than one SQL statements. 2) If you have lazy loading, then it is possible that not all statements are executed when you get the entity. – nakosspy May 13 '13 at 00:52

2 Answers2

0

Enable Hibernate Statistics in persistence.xml

<property name="hibernate.generate_statistics">true</property>

Then use SessionFactory.getStatistics() and access necessary statiscits (probably getQueries()).

For more info see Hibernate Statistics docs here or here or this post on SO.

EDIT:

If you want to do it without logging, you'll have to use JDBC driver proxy, for example log4jdbc, p6spy or jdbc-trace-wrapper.

Community
  • 1
  • 1
Mateusz
  • 3,038
  • 4
  • 27
  • 41
0

You can use show_sql, format_sql, and use_sql_comments to get the actually sql statements, in the log. Append the log to a file and parse the log using whatever tool you choose. And now, Bob's your uncle.

Community
  • 1
  • 1
hd1
  • 33,938
  • 5
  • 80
  • 91