Wednesday, February 4, 2015

Hibernate4 Logging Configuration Example

Hibernate 4.0 onwords for logging the information, JBoss Logging library are used. It is similar to SLF4J, Jakarta's Common logging, it is "logging bridge" provides the integration with several logging frameworks (Log4J, SLF4j, JDK Logging). Hibernate people is chosen JBoss Logging because it supports the I18N and support for "Message ids".

Step1: Create a Maven project
Create a maven project using one of your favorite IDE. Here i used Intellij Idea.

Step2: Update the Maven Dependencies
Update pom.xml file to include required dependencies
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.varasofttech</groupId>
<artifactId>Hibernate4LoggingExample</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Hibernate4 Logging Example</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<hiberante-version>4.3.7.Final</hiberante-version>
<log4j-version>1.2.17</log4j-version>
<mysql-version>5.1.34</mysql-version>
<junit-version>4.11</junit-version>
</properties>

<dependencies>

<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hiberante-version}</version>
</dependency>

<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-version}</version>
</dependency>

<!-- Log4J -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j-version}</version>
</dependency>

<!--JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>

</dependencies>
</project>
Step3: Create a Log4j properties file
Create a "log4j.properties" file and put it into your project’s classpath.

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Direct messages to file hibernate.log
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D://Hibernate4/hibernate.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Root logger
log4j.rootLogger=INFO, file, stdout

log4j.logger.org.hibernate=INFO

# log JDBC bind parameters
log4j.logger.org.hibernate.type=ALL

# log HQL query parser activity
log4j.logger.org.hibernate.hql.ast.AST=INFO

# log just the SQL
log4j.logger.org.hibernate.SQL=trace

# log schema export/update
log4j.logger.org.hibernate.tool.hbm2ddl=DEBUG

# log HQL parse trees
log4j.logger.org.hibernate.hql=INFO

# log cache activity
log4j.logger.org.hibernate.cache=INFO

# log JDBC resource acquisition
log4j.logger.org.hibernate.jdbc=DEBUG

Step4: Hibernate Configuration file

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///vara_softtech</property>
<property name="hibernate.connection.password">varasofttech</property>
<property name="hibernate.connection.username">varasofttech</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>

<mapping class="com.varasofttech.entity.Employee" />
</session-factory>
</hibernate-configuration>
Step5: Hibernate Utility Class
HibernateUtil.java
package com.varasofttech.util;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/**
* @author Ranga Reddy
* @date Feb 4, 2015.
* @version 1.0
*/

public class HibernateUtil {
private static SessionFactory sessionFactory = null;
private static Logger logger = Logger.getLogger(HibernateUtil.class);

public static SessionFactory getSessionFactory() {
if(sessionFactory == null) {
try {
// Create the SessionFactory from hibernate.cfg.xml
String configurationFile = "hibernate-cfg.xml";
Configuration configuration = new Configuration();
configuration.configure(configurationFile);
logger.info("Hibernate Configuration loaded successfully using "+configurationFile);
StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder();
ServiceRegistry serviceRegistry = standardServiceRegistryBuilder.applySettings(configuration.getProperties()).build();
logger.info("Hibernate serviceRegistry object created successfully");

SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
logger.info("Hibernate sessionFactory object created successfully");
return sessionFactory;
}
catch (Throwable ex) {
logger.error("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
return sessionFactory;
}
}
Step6: Client Application
Application.java

package com.varasofttech;

import com.varasofttech.entity.Employee;
import com.varasofttech.util.HibernateUtil;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
/**
* @author Ranga Reddy
* @date Feb 4, 2015
* @version 1.0
*/

public class Application {
public static void main( String[] args ) {
Logger logger = Logger.getLogger(Application.class);

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Employee employee = new Employee("Ranga Reddy", 27, 35000);
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.save(employee);
transaction.commit();
logger.info("Employee object saved successfully. Employee Info : "+employee);
} catch (Exception ex) {
transaction.rollback();
logger.info("Exception occured while saving the Employee object :", ex);
} finally {
if(transaction != null) {
transaction = null;
}
if(session != null) {
session.close();
session = null;
}
}
}
}
Hibernate.log
07:57:31,482  INFO Dialect:145 - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
07:57:32,823  INFO TransactionFactoryInitiator:62 - HHH000399: Using default transaction strategy (direct JDBC transactions)
07:57:32,869 INFO ASTQueryTranslatorFactory:47 - HHH000397: Using ASTQueryTranslatorFactory
07:57:33,100 TRACE TypeFactory:72 - Scoping types to session factory org.hibernate.internal.SessionFactoryImpl@6a2f6f80
07:57:35,771 INFO SchemaExport:343 - HHH000227: Running hbm2ddl schema export
07:57:35,774 DEBUG SchemaExport:353 - Import file not found: /import.sql
07:57:35,785 DEBUG SQL:109 - drop table if exists Employees
07:57:36,111 DEBUG SQL:109 - create table Employees (id bigint not null auto_increment, age integer, name varchar(255), salary float, primary key (id))
07:57:36,751 INFO SchemaExport:405 - HHH000230: Schema export complete
07:57:36,825 INFO HibernateUtil:31 - Hibernate sessionFactory object created successfully
07:57:37,819 DEBUG SQL:109 - insert into Employees (age, name, salary) values (?, ?, ?)
07:57:37,896 TRACE BasicBinder:81 - binding parameter [1] as [INTEGER] - [27]
07:57:37,900 TRACE BasicBinder:81 - binding parameter [2] as [VARCHAR] - [Ranga Reddy]
07:57:37,904 TRACE BasicBinder:81 - binding parameter [3] as [FLOAT] - [35000.0]
07:57:38,106 INFO Application:27 - Employee object saved successfully. Employee Info : Employee{id=1, name='Ranga Reddy', age=27, salary=35000.0}
Console log
07:57:31,482  INFO Dialect:145 - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
07:57:32,823 INFO TransactionFactoryInitiator:62 - HHH000399: Using default transaction strategy (direct JDBC transactions)
07:57:32,869 INFO ASTQueryTranslatorFactory:47 - HHH000397: Using ASTQueryTranslatorFactory
07:57:33,100 TRACE TypeFactory:72 - Scoping types to session factory org.hibernate.internal.SessionFactoryImpl@6a2f6f80
07:57:35,771 INFO SchemaExport:343 - HHH000227: Running hbm2ddl schema export
07:57:35,774 DEBUG SchemaExport:353 - Import file not found: /import.sql
07:57:35,785 DEBUG SQL:109 - drop table if exists Employees
Hibernate: drop table if exists Employees
07:57:36,111 DEBUG SQL:109 - create table Employees (id bigint not null auto_increment, age integer, name varchar(255), salary float, primary key (id))
Hibernate: create table Employees (id bigint not null auto_increment, age integer, name varchar(255), salary float, primary key (id))
07:57:36,751 INFO SchemaExport:405 - HHH000230: Schema export complete
07:57:36,825 INFO HibernateUtil:31 - Hibernate sessionFactory object created successfully
07:57:37,819 DEBUG SQL:109 - insert into Employees (age, name, salary) values (?, ?, ?)
Hibernate: insert into Employees (age, name, salary) values (?, ?, ?)
07:57:37,896 TRACE BasicBinder:81 - binding parameter [1] as [INTEGER] - [27]
07:57:37,900 TRACE BasicBinder:81 - binding parameter [2] as [VARCHAR] - [Ranga Reddy]
07:57:37,904 TRACE BasicBinder:81 - binding parameter [3] as [FLOAT] - [35000.0]
07:57:38,106 INFO Application:27 - Employee object saved successfully. Employee Info : Employee{id=1, name='Ranga Reddy', age=27, salary=35000.0}

0 comments: