Spring AOP transaction management in Hibernate

Transaction management is required to ensure the data integrity and consistency in database. Spring’s AOP technique is allow developers to manage the transaction declarative.

Here’s an example to show how to manage the Hibernate transaction with Spring AOP.

P.S Many Hibernate and Spring configuration files are hidden, only some important files are shown, if you want hand-on, download the full project at the end of the article.

1. Table creation

MySQL table scripts, a ‘product‘ table and a ‘product quantity on hand‘ table.

CREATE TABLE  `mkyong`.`product` (
  `PRODUCT_ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `PRODUCT_CODE` VARCHAR(20) NOT NULL,
  `PRODUCT_DESC` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`PRODUCT_ID`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
 
CREATE TABLE  `mkyong`.`product_qoh` (
  `QOH_ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `PRODUCT_ID` BIGINT(20) UNSIGNED NOT NULL,
  `QTY` INT(10) UNSIGNED NOT NULL,
  PRIMARY KEY (`QOH_ID`),
  KEY `FK_product_qoh_product_id` (`PRODUCT_ID`),
  CONSTRAINT `FK_product_qoh_product_id` FOREIGN KEY (`PRODUCT_ID`) 
  REFERENCES `product` (`PRODUCT_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2. Product Business Object

In this ‘productBo‘ implementation, the save() method will insert a record into the ‘product‘ table via ‘productDao‘ class and a quantity on hand record into the ‘productQoh‘ table via ‘productQohBo‘ class.

package com.mkyong.product.bo.impl;
 
import com.mkyong.product.bo.ProductBo;
import com.mkyong.product.bo.ProductQohBo;
import com.mkyong.product.dao.ProductDao;
import com.mkyong.product.model.Product;
import com.mkyong.product.model.ProductQoh;
 
public class ProductBoImpl implements ProductBo{
 
	ProductDao productDao;
	ProductQohBo productQohBo;
 
	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}
 
	public void setProductQohBo(ProductQohBo productQohBo) {
		this.productQohBo = productQohBo;
	}
 
	//this method need to be transactional
	public void save(Product product, int qoh){
 
		productDao.save(product);
		System.out.println("Product Inserted");
 
		ProductQoh productQoh = new ProductQoh();
		productQoh.setProductId(product.getProductId());
		productQoh.setQty(qoh);
 
		productQohBo.save(productQoh);
		System.out.println("ProductQoh Inserted");
	}
}

Spring’s bean configuration file.

   <!-- Product business object -->
   <bean id="productBo" class="com.mkyong.product.bo.impl.ProductBoImpl" >
   	<property name="productDao" ref="productDao" />
   	<property name="productQohBo" ref="productQohBo" />
   </bean>
 
   <!-- Product Data Access Object -->
   <bean id="productDao" class="com.mkyong.product.dao.impl.ProductDaoImpl" >
   	<property name="sessionFactory" ref="sessionFactory"></property>
   </bean>

Run it

	Product product = new Product();
    product.setProductCode("ABC");
    product.setProductDesc("This is product ABC");
 
    ProductBo productBo = (ProductBo)appContext.getBean("productBo");
    productBo.save(product, 100);

Assume the save() does not has the transactional feature, if an Exception throw by productQohBo.save(), you will insert a record into ‘product‘ table only, no record will be insert into the ‘productQoh‘ table. This is a serious problem and break the data consistency in your database.

3. Transaction Management

Declared a ‘TransactionInterceptor‘ bean, and a ‘HibernateTransactionManager‘ for the Hibernate transaction, and passing the necessary property.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <bean id="transactionInterceptor" 
       class="org.springframework.transaction.interceptor.TransactionInterceptor">
	<property name="transactionManager" ref="transactionManager" />
	<property name="transactionAttributes">
	   <props>
		<prop key="save">PROPAGATION_REQUIRED</prop>
	   </props>
	</property>
    </bean>
 
    <bean id="transactionManager" 
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
	  <property name="dataSource" ref="dataSource" />
	  <property name="sessionFactory" ref="sessionFactory" />
    </bean>
 
</beans>
Transaction Attributes

In transaction interceptor, you have to define which transaction’s attributes ‘propagation behavior‘ should be use. It means if a transactional ‘ProductBoImpl.save()‘ method is called another method ‘productQohBo.save()‘, how the transaction should be propagated? Should it continue to run within the existing transaction? or start a new transaction for its own.

There are 7 types of propagation supported by Spring :

  • PROPAGATION_REQUIRED – Support a current transaction; create a new one if none exists.
  • PROPAGATION_SUPPORTS – Support a current transaction; execute non-transactionally if none exists.
  • PROPAGATION_MANDATORY – Support a current transaction; throw an exception if no current transaction exists.
  • PROPAGATION_REQUIRES_NEW – Create a new transaction, suspending the current transaction if one exists.
  • PROPAGATION_NOT_SUPPORTED – Do not support a current transaction; rather always execute non-transactionally.
  • PROPAGATION_NEVER – Do not support a current transaction; throw an exception if a current transaction exists.
  • PROPAGATION_NESTED – Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.

In most cases, you may just need to use the PROPAGATION_REQUIRED.

In addition, you have to define the method to support this transaction attributes as well. The method name is supported wild card format, a save* will match all method name start with save(…).

Transaction Manager

In Hibernate transaction, you need to use HibernateTransactionManager. If you only deal with pure JDBC, use DataSourceTransactionManager; while JTA, use JtaTransactionManager.

4. Proxy Factory Bean

Create a new proxy factory bean for ProductBo, and set the ‘interceptorNames‘ property.

   <!-- Product business object -->
   <bean id="productBo" class="com.mkyong.product.bo.impl.ProductBoImpl" >
   	<property name="productDao" ref="productDao" />
   	<property name="productQohBo" ref="productQohBo" />
   </bean>
 
   <!-- Product Data Access Object -->
   <bean id="productDao" class="com.mkyong.product.dao.impl.ProductDaoImpl" >
   	<property name="sessionFactory" ref="sessionFactory"></property>
   </bean>
 
   <bean id="productBoProxy"
	class="org.springframework.aop.framework.ProxyFactoryBean">
	<property name="target" ref="productBo" />
	<property name="interceptorNames">
		<list>
			<value>transactionInterceptor</value>
		</list>
	</property>
  </bean>

Run it

    Product product = new Product();
    product.setProductCode("ABC");
    product.setProductDesc("This is product ABC");
 
    ProductBo productBo = (ProductBo)appContext.getBean("productBoProxy");
    productBo.save(product, 100);

Get your proxy bean ‘productBoProxy‘, and your save() method is support transactional now, any exceptions inside productBo.save() method will cause the whole transaction to rollback, no data will be insert into the database.

Download Source Code

References

  1. http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/transaction/TransactionDefinition.html
  2. http://static.springsource.org/spring/docs/2.5.x/reference/transaction.html
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: learn more()

  • Pingback: right here()

  • Pingback: water ionizer()

  • Pingback: water ionizer payment plan()

  • Pingback: pay per day loan plans()

  • Pingback: bottled alkaline water()

  • Pingback: payment plan()

  • Pingback: water ionizers()

  • Pingback: h&a nyc electrician()

  • Pingback: house blue()

  • Pingback: zak?ad szklarski piotrków trybunalski()

  • Pingback: plumbers putty faucet()

  • Pingback: electrician apprenticeship()

  • Pingback: paypal loans()

  • Pingback: penge laan nu()

  • Pingback: stop parking()

  • Pingback: lane penge()

  • Pingback: parking()

  • Pingback: mobile porn()

  • Pingback: tvpackages.net()

  • Pingback: best DIRECTV deals()

  • Pingback: best online casinos()

  • Pingback: Blue Coaster33()

  • Eric

    Good post, but imho it’s not an AOP basic configuration, regards, Eric.

  • Deepak

    Hi,
    I m a newbie.When i tried running your example in my eclipse i get the following error:

    log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
    log4j:WARN Please initialize the log4j system properly.
    Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in class path resource [spring/database/DataSource.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
    PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property ‘driverClassName’ threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1279)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
    at com.mkyong.common.App.main(App.java:13)
    Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
    PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property ‘driverClassName’ threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:104)
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:59)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1276)
    … 16 more

    PLZ…..HELP ME UP

  • http://Mathalan.com sara

    Niyamay Yong oya nam pattama weda karayek

  • rio

    hi…
    have you try nested transaction with spring ?

  • Yadab Raj Ojha

    Very much clean and complete project! Thank u so much mkyoung for your great post. It works for me without any error in eclipse as well as in netbean(after just copy + paste of source package)*****5star

  • FTorterolo

    Muchas gracias, fue de mucha ayuda para mi tarea.

  • Manjeet Rulhania

    thanks a ton :)

  • jagan

    Nice Tutorial ..,
    good work.

  • John

    Hi,

    Is this really a SPRING AOP TRANSACTION MANAGEMENT, then where are the adivce and point cuts …. i think this eaxmple is SPRING DECLARATIVE PROXY BASED example not the AOP based.
    Can you please change the title of of project as many of them will get confused..

    John

  • Solipuram

    Hi MK,

    Regularly i am following your site for upgrading my knowledge thanks for your post.

    I have one problem in spring transaction.
    The above example is working fine for me when i am running as a stand alone application, but when i am trying to implement same transaction support in my web application it’s not working can you guide me please.

    Thanks in advance.

    • Solipuram

      Above issue is resolved.
      Problem is in my code i handled the exceptions in try catch so the method is executing normally so it can’t performed the rollback operation.

  • appesh

    Thnks..useful

  • Anil Kumar

    What is the difference between PROPAGATION_REQUIRES_NEW and PROPAGATION_NESTED . ?
    In both cases if transaction already exists will create a new sub transaction .

  • Vivek

    I find your posts/tutorials very helpful.
    Keep up the good work.

    I was however not able to build the project on the pom from the zip.
    Could you please confirm that it is correct?

    I am getting an error for

    	&lt;dependency&gt;
    		&lt;groupId&gt;hibernate&lt;/groupId&gt;
    		&lt;artifactId&gt;hibernate3&lt;/artifactId&gt;
    		&lt;version&gt;3.2.3.GA&lt;/version&gt;
    	&lt;/dependency&gt;
    [ERROR] Failed to execute goal on project SpringExample: Could not resolve dependencies for project com.mkyong.common:SpringExample:jar:1.0-SNAPSHOT: Failure t
    o find hibernate:hibernate3:jar:3.2.3.GA in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -&gt; [Help 1]
    • JSF_Learner

      Is this Error of yours Resolved?

    • appesh

      Google the maven dependencies for hibernate and replace it will work fine.

      • Shakhal Levinson

        org.hibernate
        hibernate-entitymanager
        3.3.2.GA

  • http://.html Elroy Willoughby

    Fascinating post. I’ll be sticking about to hear significantly a lot more from you guys. Thanks!

  • raza

    can u please post code using AOP

  • Raghu

    How to check if there was rollback? Is there a way to find the status of transaction on individual tables.

    Example:

    In a single method called checkout,there are insertion on tables and then a confirmation email is sent.

    This method is declaratively wrapped by transaction.

    I want to know if the sql’s are ok before sending email.

    • raza

      It’s better not to put send email in trnasaction as the tables will be locked by the transaction till the transaction is completed. You can have after transaction event method.

      • husain

        thanks for the reply.

      • http://www.azizkhani.net ali akbar azizkhani

        mishe begi chi neveshti :D

  • http://gabhi.com Abhijit

    I am getting following error

    Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘productBoProxy': FactoryBean threw exception on object creation; nested exception is org.springframework.aop.framework.AopConfigException: Unknown advisor type class org.springframework.transaction.interceptor.TransactionInterceptor; Can only include Advisor or Advice type beans in interceptorNames chain except for last entry,which may also be target or TargetSource; nested exception is org.springframework.aop.framework.adapter.UnknownAdviceTypeException: Advice object [org.springframework.transaction.interceptor.TransactionInterceptor@65d9e279] is neither a supported subinterface of [org.aopalliance.aop.Advice] nor an [org.springframework.aop.Advisor]

    I m a newbie, in your source code are you missing productBoProxy?

  • Gaurav

    Hi mk :)

    I am getting an error while trying to run this tutorial as follows

    Error creating bean with name ‘sessionFactory’ defined in class path resource [spring/database/Hibernate.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager

    Please help me ….

    • http://www.mkyong.com mkyong

      you need javee.jar, which you can locate in JavaEE SDK.

  • Mohamed

    transaction rollback not working right: If I have an exception in insert ProductQoh the insert of Product does not get rolled back.

    • Ryan

      Yes me too, transaction rollback aint working right

      • Raza

        Transaction rollback worked perfectly for me. Are you using spring declarative transactions. Please feel free to elaborate you problem, I have done enough research on this.

        • Auton

          Hi Raza, I’m facing the same problem like Mohamed and Ryan does.
          I’m running the code as I had downloaded from here. Have you changed
          something in the source code to make transaction to be rolled-back properly?

          • Vijay

            Good job. Appreciate it.

            -Vijay

        • jerry

          Hi,

          I am facing that Exception while running the program

          Error creating bean with name ‘sessionFactory’ defined in class path resource [Hibernate.xml]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.slf4j.impl.JDK14LoggerAdapter.isTraceEnabled()Z

          Please help me to resolve that.

          Thanks

  • Pingback: Spring Tutorials | Tutorials()