Friday, January 15, 2016

Logging Hibernate Query

To log Hibernate SQL queries, we need to set below properties to true in the configuration of the session factory (only the first one is mandatory).

<property name="hibernate.show.sql" value="true" />
<property name="hibernate.format.sql" value="true" />
<property name="hibernate.use.sql.comments" value="true" />

show.sql : logs SQL queries
format.sql: pretty prints the SQL
use.sql.comments: adds explanatory comment

This is how a sample query will look like, after enabling above properties:

/* insert com.co.orm.AuditLogRecord  */
insert into 
audit_log
(creationTime, createdBy, deleted, name, operationType, rowId, details)
values
(?,?,?,?,?,?,?,?)

Decoding Above Query

Hibernate logs above query which gets sent to the JDBC driver. Hibernate logs prepared statement and that's why you are seeing? instead of the actual values.

Hibernate only knows about the prepared statement that it sends to the JDBC driver.  It's JDBC driver that builds the actual query and sends them to the database for execution.

This means that, if you want Hibernate to log the actual SQL query with the value embedded, it would have to generate them for you just for logging! 

If you want to see actual query:

No comments:

Post a Comment