Hibernate 5 + Log4j 2 configuration example

Posted on May 4, 2017


In this post, we will learn how to setup the Log4j 2 logging framework to log sql statements and JDBC bind parameters in Hibernate application.

Tool and technologies used –

  • JDK 1.8.0_121
  • Maven 3.3.9
  • Eclipse Neon.3
  • Hibernate 5.2.9.Final
  • Log4j 2.8.2
  • MySQL Server 5.7.12

Let’s write a sample hibernate application to log SQL statement and bind parameters. 

Project structure

Review the following maven project structure.

hibernate5-log4j2-ps.png

Refer this article to learn - How to create a maven project in eclipse.

Jar dependencies

Edit pom.xml file and add Hibernate, Log4j and MySQL dirver dependencies in it as follows.

  <dependencies>
    <!-- Mysql Connector -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>
    <!-- Hibernate 5.2.9 Final -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.9.Final</version>
    </dependency>

    <!--Log4j2 API -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.8.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.8.2</version>
    </dependency>
  </dependencies>

XML configuration file for Log4j 2 

Create a log4j2.xml file under src/main/resources source folder.

Add the following logger definition to the log4j2.xml file to log sql statements.

<Logger name="org.hibernate.SQL" level="debug" additivity="false">
  <AppenderRef ref="Console" />
</Logger>

If you want to log JDBC bind parameters then add the following logger definition to the log4j2.xml file.

<Logger name="org.hibernate.type.descriptor.sql" level="trace" additivity="false">
  <AppenderRef ref="Console" />
</Logger>

Here is the complete Log4j 2 configuration file.

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>

    <!-- Console Appender -->
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
    </Console>

    <!-- File Appender -->
    <File name="File" fileName="c:/log/app.log">
      <PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
    </File>

  </Appenders>
  <Loggers>
    <!-- Log everything in hibernate -->
    <Logger name="org.hibernate" level="info" additivity="false">
      <AppenderRef ref="Console" />
    </Logger>

    <!-- Log SQL statements -->
    <Logger name="org.hibernate.SQL" level="debug" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

    <!-- Log JDBC bind parameters -->
    <Logger name="org.hibernate.type.descriptor.sql" level="trace" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

    <!-- Log custom packages -->
    <Logger name="com.boraji.tutorial.hibernate" level="debug" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

    <Root level="error">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Root>
  </Loggers>
</Configuration>

 

Entity class

Create an @Entity class under com.boraji.tutorial.hibernate.entity package.

Customer.java

package com.boraji.tutorial.hibernate.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author imssbora
 */
@Entity
@Table(name = "CUSTOMER_TBL")
public class Customer {
  @Id
  @GeneratedValue
  @Column(name = "CUST_ID")
  private Long id;

  @Column(name = "NAME")
  private String name;

  // Getter and Setter methods
}

Hibernate utility class

Create a helper class HibernateUtil to bootstrap hibernate.

HibernateUtil.java

package com.boraji.tutorial.hibernate;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;

import com.boraji.tutorial.hibernate.entity.Customer;

public class HibernateUtil {

   private static final Logger logger = LogManager.getLogger(HibernateUtil.class);

   private static StandardServiceRegistry registry;
   private static SessionFactory sessionFactory;

   public static SessionFactory getSessionFactory() {
      if (sessionFactory == null) {
         try {
            StandardServiceRegistryBuilder registryBuilder = 
                  new StandardServiceRegistryBuilder();
            
            Map<String, String> settings = new HashMap<>();
            settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
            settings.put(Environment.URL, "jdbc:mysql://localhost:3306/BORAJI");
            settings.put(Environment.USER, "root");
            settings.put(Environment.PASS, "admin");
            settings.put(Environment.HBM2DDL_AUTO, "update");

            registryBuilder.applySettings(settings);

            registry = registryBuilder.build();

            logger.info("Hibernate Registry builder created.");
            
            MetadataSources sources = new MetadataSources(registry).addAnnotatedClass(Customer.class);

            Metadata metadata = sources.getMetadataBuilder().build();

            sessionFactory = metadata.getSessionFactoryBuilder().build();
            
            logger.info("SessionFactory created.");
            
         } catch (Exception e) {
            logger.info("SessionFactory creation failed");
            if (registry != null) {
               StandardServiceRegistryBuilder.destroy(registry);
            }
         }
      }
      return sessionFactory;
   }

   public static void shutdown() {
      if (registry != null) {
         StandardServiceRegistryBuilder.destroy(registry);
      }
   }
}

Run Application

Create the MainApp class to test the above Log4j2 and Hibernate configuration.

MainApp.java

package com.boraji.tutorial.hibernate;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.boraji.tutorial.hibernate.entity.Customer;

/**
 * @author imssbora
 */
public class MainApp {

   private static final Logger logger = LogManager.getLogger(MainApp.class);

   public static void main(String[] args) {
      Session session = null;
      Transaction transaction = null;
      try {
         session = HibernateUtil.getSessionFactory().openSession();
         transaction = session.getTransaction();
         transaction.begin();

         Customer customer = new Customer();
         customer.setName("Joe");
         session.persist(customer);

         transaction.commit();

         logger.info("Customer saved successfully...");

      } catch (Exception e) {
         if (transaction != null) {
            transaction.rollback();
         }
         logger.error("Failed to save customer..." + e);
      } finally {
         if (session != null) {
            session.close();
         }
      }

      HibernateUtil.shutdown();
   }
}

Output

hibernate5-log4j2-log.png

 

Download Sources