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.
why you create Proxy there?
What is the benefit of adding proxy?/interceptor
PROPAGATION_REQUIRED
transactionInterceptor
P.S Many Hibernate , here P.S means??
In eclipse Eclipse->Properties -> Java Build Path -> Libraries and removed the blue entries starting with “M2_REPO”
Also update in pom.xml old hibernate dependencies http://search.maven.org/#search%7Cga%7C1%7C
Hi,
nice tutorial, but one doubt- How can I add another DAO or Service class into the target property for the same proxyfactory bean Or do I have to have a seperate transactionproxyBean for each DAO /Service class .
Thanks, nice post
Good post, but imho it’s not an AOP basic configuration, regards, Eric.
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
Niyamay Yong oya nam pattama weda karayek
hi…
have you try nested transaction with spring ?
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
Muchas gracias, fue de mucha ayuda para mi tarea.
thanks a ton 🙂
Nice Tutorial ..,
good work.
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
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.
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.
Thnks..useful
What is the difference between PROPAGATION_REQUIRES_NEW and PROPAGATION_NESTED . ?
In both cases if transaction already exists will create a new sub transaction .
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
http://mvnrepository.com/artifact/org.hibernate/hibernate/3.2.3.ga
Google the maven dependencies for hibernate and replace it will work fine.
org.hibernate
hibernate-entitymanager
3.3.2.GA
Is this Error of yours Resolved?
Fascinating post. I’ll be sticking about to hear significantly a lot more from you guys. Thanks!
can u please post code using AOP
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.
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.
mishe begi chi neveshti 😀
thanks for the reply.
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 ….
you need javee.jar, which you can locate in JavaEE SDK.
transaction rollback not working right: If I have an exception in insert ProductQoh the insert of Product does not get rolled back.
Yes me too, transaction rollback aint working right
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.
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
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?
Good job. Appreciate it.
-Vijay
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?