05: Debugging Hibernate & handling 4 common issues

#1. Enable Logging in your log4j.xml, log4j.properties, or myapp-logback.xml

In the log4j.properties file, you can enable Hibernate SQL logging as shown below

or in your log4j.xml or myapp-logback.xml as

You can then check your logs for the SQLs executed and the parameters passed. The example below shows 3 parameters passed to an update query

#2. Setting show_sql to true in the hibernate configuration for development only

Spring application context file example. Note the last 3 entries:

#3. P6Spy (or log4jdbc) to see the SQL directly sent to the database

This approach is more intrusive, but is way more powerful. It consists of putting a proxy driver between JDBC and the real driver so that all generated SQL will be logged.

Step 1: Add P6Spy driver to the Maven pom.xml

Step 2: Tell hibernate to use “com.p6spy.engine.spy.P6SpyDriver”

Step 3: In the spy.properties

If you need to use P6Spy in an application server, the configuration should be done on the application server itself, at the datasource level.

#4. Knowing what the common hibernate errors are and how to fix them

There are some very common mistakes made due to lack of understanding of how Hibernate works. Here are very detailed posts on Hibernate common issues, and how to go about fixing them.

1. Hibernate mistakes – accessing objects outside of a transaction

2. Understanding Hibernate proxy objects and avoiding potential pitfalls

3. Identifying and fixing LazyInitializationException in Hibernate

4. Identifying and fixing NonUniqueObjectException in Hibernate


Answers are detailed to be useful beyond job interviews. A few Q&As each day will make a huge difference in 3 to 24 months to go places depending on your experience.
Top