Hibernate Logging and Statistics

This article cover how to do logging in Hibernate with SLF4j + Log4j logging framework. You also see the use of Show_sql , Format_sql and Use_sql_comments.

You’ve seen the hibernate.show_sql configuration property in our many articles. You’ll need it continually when you develop software with Hibernate; it enables logging of all generated SQL to the console. You’ll use it for troubleshooting, for performance tuning, and to see what’s going on. If you also enable hibernate.format_sql, the output is more readable but takes up more screen space. A third option you haven’t set so far is hibernate.use_sql_comments – it causes Hibernate to put comments inside all generated SQL statements to hint at their origin. For example, you can then easily see if a particular SQL statement was generated from an explicit query or an on-demand collection initialization.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml


1. Show_sql

Enable the logging of all the generated SQL statements to the console.

<property name="show_sql">true</property>

Output is :

Hibernate: insert into EMPLOYEE (NAME) values (?)

2. Format_sql

If you also enable hibernate.format_sql, the output is more readable but takes up more screen space

<property name="format_sql">true</property>

Output is :


3. Use_sql_comments

It causes Hibernate to put comments inside all generated SQL statements to hint at their origin.

<property name="use_sql_comments">true</property>

Output is :

    /* insert com.kruders.bean.Employee
        */ insert 

4. Log4j

Hibernate logs all interesting events through Apache commons-logging, a thin abstraction layer that directs output to either Apache Log4j (if you put log4j.jar in your classpath) or JDK 1.4 logging (if you’re running under JDK 1.4 or above and Log4j isn’t present). We recommend Log4j because it’s more mature, more popular, and under more active development.

To see output from Log4j, you need a file named log4j.properties in your classpath (right next to hibernate.properties or hibernate.cfg.xml). Also, don’t forget to copy the log4j.jar library to your lib directory. The Log4j configuration example in listing 1.1 directs all log messages to the console and a file.

Listing below shows an example log4j.properties configuration file

# Direct log messages to stdout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Direct log messages to a log file
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Root logger option
log4j.rootLogger=INFO, stdout, file
# Hibernate logging options (INFO only shows startup messages)
# Log JDBC bind parameter runtime arguments

The last category in this configuration file is especially interesting: It enables the logging of JDBC bind parameters if you set it to DEBUG level, providing information you usually don’t see in the ad hoc SQL console log.

5. Run Program

Create Main.java class and run it as Java Application

package com.kruders.core;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import com.kruders.bean.Employee;
import com.kruders.util.HibernateUtil;

public class Main {
	public static void main(String args[]) throws InterruptedException {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
        try {
        	transaction = session.beginTransaction();
            Employee employee = new Employee("Puneet");
        }catch (HibernateException e) {
        } finally {

You will see the following output as shown in Figure 15.1

Figure 15.1 Figure 15.1

HibernateLogging.log file will be created under C:\

It contains the similar content as shown below.

12:08:09,515  INFO Configuration:2270 - Configured SessionFactory: null
12:08:09,578  INFO AnnotationBinder:532 - Binding entity from annotated class: com.kruders.bean.Employee
12:08:09,609  INFO EntityBinder:530 - Bind entity com.kruders.bean.Employee on table EMPLOYEE
12:08:09,640  INFO Configuration:1649 - Hibernate Validator not found: ignoring
12:08:09,640  INFO HibernateSearchEventListenerRegister:75 - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
12:08:09,640  INFO DriverManagerConnectionProvider:64 - Using Hibernate built-in connection pool (not for production use!)
12:08:09,640  INFO DriverManagerConnectionProvider:65 - Hibernate connection pool size: 1
12:08:09,640  INFO DriverManagerConnectionProvider:68 - autocommit mode: false
12:08:09,656  INFO DriverManagerConnectionProvider:103 - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/test
12:08:09,656  INFO DriverManagerConnectionProvider:109 - connection properties: {user=root, password=****}
12:08:09,843  INFO Dialect:135 - Using dialect: org.hibernate.dialect.MySQLDialect
12:08:09,843  INFO SettingsFactory:126 - Database ->
       name : MySQL
    version : 5.5.24
      major : 5
      minor : 5
12:08:09,843  INFO SettingsFactory:132 - Driver ->
       name : MySQL-AB JDBC Driver
    version : mysql-connector-java-5.1.15 ( Revision: ${bzr.revision-id} )
      major : 5
      minor : 1
12:08:09,843  INFO TransactionFactoryFactory:59 - Using default transaction strategy (direct JDBC transactions)
12:08:09,843  INFO TransactionManagerLookupFactory:80 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
12:08:09,843  INFO SettingsFactory:179 - Automatic flush during beforeCompletion(): disabled
12:08:09,843  INFO SettingsFactory:183 - Automatic session close at end of transaction: disabled
12:08:09,843  INFO SettingsFactory:190 - JDBC batch size: 15
12:08:09,843  INFO SettingsFactory:193 - JDBC batch updates for versioned data: disabled
12:08:09,843  INFO SettingsFactory:198 - Scrollable result sets: enabled
12:08:09,843  INFO SettingsFactory:206 - JDBC3 getGeneratedKeys(): enabled

The folder structure of the example is shown below in Figure 15.2

Figure 15.2 Figure 15.2

You can download the source code of this example here.

No comments yet.

Leave a Reply