Tech I Enjoy Logo

Custom Search




  Home >> Hibernate


Interceptors can be used in cases where we may require
some sort of callback methods called just before the
actual operation is called. For example If it is required
to log any perticular SQL in some different log/audit file,
then we can set a simple Interceptor like CaptureSQL or
LogSQL, just while opening Sesson using SessionFactory
openSession (Interceptor) method.

Following sample interceptor does the logging of SQL
on prepare statement.


import org.apache.log4j.Logger;
import org.hibernate.EmptyInterceptor;

public class CaptureSQL extends EmptyInterceptor {
    private static Logger log = Logger.getLogger("L1");
	public String onPrepareStatement(String sql) {
		log.debug("Loging SQL statement ...... start");
		log.debug(sql);
		log.debug("Loging SQL statement ...... end");
		return sql;
	}
}
CaptureSQL is the user defined class that extends org.hibernate.EmptyInterceptor to become receiving callback overridden method, such as "onPrepareStatement", when ever a Session is opened, by calling SessionFactory.openSession(new CaptureSQL()). Appropriate log4j.properties file should be configured to be able to handle these logging part. My sample log4j.properties file is as follows:
log4j.rootLogger=DEBUG
log4j.logger.L1=INHERIT, L
log4j.appender.L=org.apache.log4j.FileAppender
log4j.appender.L.file=sample.txt
log4j.appender.L.layout=org.apache.log4j.PatternLayout
log4j.appender.L.layout.ConversionPattern=%d [%t] %C{1} - %m%n
And the Client code is as follows: Client.java (Hibernate one to one mapping Test main class)
// This source is provided on "AS IS" basis.
import java.util.Calendar;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import org.apache.log4j.Logger;

public class Client {

    private static final SessionFactory sessionFactory;
    static {
      try {
         // Create the SessionFactory from hibernate.cfg.xml
         sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public static void createRecord()
    {
		Session session = getSessionFactory().openSession(new CaptureSQL());
		Transaction trx = session.beginTransaction();
		trx.begin();
		Car car = new Car();
		car.setCarName("My Car1");
		car.setModel("My Model1");
		car.setSegment("My Segment1");
        session.persist(car);
		
		trx.commit();
		session.close();
    }
 	/**
	 * @param args
	 */
	public static void main(String[] args) {

		createRecord();
	}

}
hibernate.cfg.xml (configuration file for creation of Hibernate session factory)
// This source is provided on "AS IS" basis.
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
    <property name="connection.driver_class">
		  org.hsqldb.jdbcDriver
    </property>
    <property name="connection.url">
		  jdbc:hsqldb:hsql://localhost/
    </property>
    <property name="connection.username">sa</property>
    <property name="connection.password"></property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">
		  org.hibernate.dialect.HSQLDialect
	</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">
		  thread
	</property>

		<!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <mapping resource="car.hbm.xml"/>

    </session-factory>

</hibernate-configuration>
This example domain class "Car.java" file is as follows:
// This source is provided on "AS IS" basis.

public class Car {
  private String carName;
  private String model;
  private String segment;
  
  public String getCarName() {
	return carName;
  }
  public void setCarName(String carName) {
	this.carName = carName;
  }
  public String getModel() {
	return model;
  }
  public void setModel(String model) {
	this.model = model;
  }
  public String getSegment() {
	return segment;
  }
  public void setSegment(String segment) {
	this.segment = segment;
  }
}
And the corresponding Hibernate HBM configuration file is as follows:
// This source is provided on "AS IS" basis.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="Car" table="Car">
  	<id name="carName" access="property" column="car_name"/>
 	<property name="model" column="car_model"/>
  	<property name="segment" column="car_segment"/>
  </class>
</hibernate-mapping>
In order to execute this example, you may have to create relevant table (the DDL as shown below) or use appropriate configuration entry for creation of database table at runtime.
// This source is provided on "AS IS" basis.
create table car
(car_name varchar(20), car_model varchar(50), 
 car_segment varchar(50), primary key (car_name));
On executing Client code, we can see logs are getting written onto the sample.txt log file, as shown follows: 2009-01-04 09:01:11,578 [main] CaptureSQL - Loging SQL statement .start 2009-01-04 09:01:11,593 [main] CaptureSQL - This is a log statement before onPrepareStatement: <<The DML used in this operation on the Session opened with CatureSQL as interceptor>> 2009-01-04 09:01:11,593 [main] CaptureSQL - Loging SQL statement .end There are many other interesting callback methods can be used from EmptyInterceptor, such as findDirty -> to check where the Entity in use is dirty or not. -> if this method returns an empty int[] array, then the Entity object supplied in argument of this method is not dirty. -> if this method returns an empty int[] array, then the Entity object is dirty or is updated by some other process in database. -> by returning a null from the overridden findDirty method one can opt for using Hibernate's own or default dirty checking mechanism. onLoad -> it is called just before Entity object is initialized. onDelete -> it is called just before Entity object is deleted. and many more callback methods as defined in org.hibernate.Intercept interface. Hibernate Question on Interceptor 2: Can there be any Interceptor for SessionFactory, so that it can be used across all the Session from this SessionFactory? Yes, there can be an Interceptor defined in org.hibernate.cfg.Configuration to be defined during SessionFactory creation. Configuration.setInterceptor method can be used for this purpose. Hibernate Question on Interceptor 3: Can one be able to use Hibernate Session from within the callback methods of Interceptor? No, Session may not be used from the callback methods of Interceptor. Hibernate Question on Interceptor 4: Can the collection be recreated/initialized lazily while executing any callback method from Interceptor? No, Collection may not be lazily initialized, from callback method of Interceptors. Interceptors in Hibernate Framework can be of two different scopes, such as session scoped and session factory scoped. In this example and above code is implemented using Hibernate sesssion scoped interceptors in mind. In the following section we shall re-create this example using Hibernate session factory scoped interceptor. Just you have to do is to change the static initializer block in the Client program, and set appropriate interceptor instance into the Configuration instance, and use this interceptor while building Hibernate session factory. And of course you may open session with no interceptor instance passed as constructor argument in the createRecord method. Code snippet as shown below:
// This source is provided on "AS IS" basis.
    static {
      try {
         // Create the SessionFactory from hibernate.cfg.xml
         sessionFactory = new Configuration().setInterceptor(new CaptureSQL()).configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
If you like to share your comment/suggestions/feedback relating to this Page, you can do so by droping us an email at usingframeworks @ gmail . com with the subject line mentioning URL for this Page (i.e, /Hibernate-Interceptor-example.php) or use this LINK. As per this website's privacy policy, we never disclose your email id, though we shall post your comments/suggestions/feedback with your name (optional) and date on this Page. If you don't want your comments/suggestions/feedback to be shared in this Page, please mention so in your email to us. Thank you very much..... If anything missed out , please let me know at techienjoy at yahoo . com
Example on persisting Class Hierarchy :
Example on using Hibernate Framework
to persist Class Hierarchy into database.
Hibernate class heirarchy mapping :
Hibernate Example on mapping
class hierarchy using various ways
of persisting into database
tables.
Hibernate Example on Filter Criteria :
Example on using Filter Criteria
using Hibernate Framework to work with.
List of Examples on Hibernate :
List of example using Hibernate.
Hibernate Example on composite Primary key :
Example on using Hibernate Framework
to work with mapping using composite
Primary key.
Hibernate Join Example :
Using Table join explained with an example
while using Hibernate Framework.
Hibernate Property Formula :
Hibernate Example on Property
Tag with ease to do code walk-through
Hibernate Component Property :
Hibernate Example on Component 
with source code explained.
Hibernate Insert Update control :
Hibernate Example on controlling
insert and update attributes
Hibernate Many to Many Mapping Example :
Many to many mapping example using Hibernate
Framework and a simple to follow steps.
Hibernate one to one mapping Example :
one to one mapping explained using an example
and Hibernate Framework.
Class Hierarchy Mapping Example :
class hierarchy mapping example using Hibernate
Framework and a simple to follow steps.
Hibernate Named Query Example :
Named Query markup using an example
and Hibernate Framework.
Hibernate Interview Questions :
Interview Questions on Hibernate with answer.
Hibernate Interceptor Example :
Example on using Interceptor using Hibernate Framework
with source code explained.
Hibernate Transaction on JBoss :
Explaining Transaction using Hibernate
on JBoss Application Server.
Hibernate Example on Filter :
Example on using Filter using Hibernate Framework
to work with.
Hibernate one to many mapping Example :
one to many mapping explained using an example
and Hibernate Framework.
Hibernate one to many mapping Example :
one to many mapping explained using an example
and Hibernate Framework.
Hibernate Bag Mapping Example :
class mapping using Bag Tag example using Hibernate
Framework and a simple to follow steps.


References :
Tags: Hibernate Class Hierarchy Persist example
Tags: Hibernate composite primary key
Tags: Hibernate criteria filter example
Tags: Hibernate Filter Example
Tags: Hibernate Interceptor example
Tags: Hibernate Interview Questions
Tags: Hibernate join example
Tags: Hibernate Many to Many Mapping Example
Tags: Hibernate mapping bag
Tags: Hibernate mapping class hierarchy table per subclass
Tags: Hibernate named query markup
Tags: Hibernate One to Many mapping example
Tags: Hibernate One To One Mapping Example
Tags: Hibernate scenario one to many
Tags: Hibernate transaction jboss
Tags: Hibernate



DISCLAIMER :
The content provided in this page is not warranted and/or guaranteed by techienjoy.com. 
techienjoy.com is not liable for any negative consequences that may result/arise from 
implementing directly/indirectly any information covered in these pages/articles/tutorials.

All contents of this site is/are written and provided on an "AS IS" basis,
without WARRANTIES or conditions of any kind, either express or implied, including, without
limitation, merchantability, or fitness for a particular purpose. You are solely responsible
for determining the appropriateness of using or refering this and assume any risks associated
with this.

In spite of all precautions taken to avoid any typo in these pages, there might be some 
issues like grammatical mistakes and typos being observed in these pages, techienjoy.com
extends sincerest apologies to all our visitors for the same.



Android Examples || Android Examples

© Copyright 2010-2012, TECHIENJOY, All Rights Reserved.      Privacy Policy     Disclaimer & Terms & Conditions