Spring @EnableTransactionManagement Annotation
November 25, 2021
This page will walk through Spring @EnableTransactionManagement
annotation example.
1. The
@EnableTransactionManagement
enables annotation-driven transaction management capability. It is used on @Configuration
classes.
2. The
@EnableTransactionManagement
configures traditional, imperative transaction management or reactive transaction management.
3. For imperative transaction management, create a bean of
PlatformTransactionManager
in configuration class.
4. For reactive transaction management, create a bean of
ReactiveTransactionManager
in configuration class.
5. The
<tx:annotation-driven/>
XML namespace is equivalent to @EnableTransactionManagement
annotation.
6. The
@EnableTransactionManagement
is used as following.
@Configuration @EnableTransactionManagement public class AppConfig { }
Complete Example
AppConfig.javapackage com.concretepage; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.HibernateTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.concretepage.persistence.User; @Configuration @EnableTransactionManagement public class AppConfig { @Bean public User user() { return new User(); } @Bean public HibernateTemplate hibTemp() { return new HibernateTemplate(sessionFactory(), true); } @Bean public SessionFactory sessionFactory() { SessionFactory sf = new AnnotationConfiguration().configure() .buildSessionFactory(); return sf; } @Bean public HibernateTransactionManager hibTransMan(){ return new HibernateTransactionManager(sessionFactory()); } }
package com.concretepage; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.orm.hibernate3.HibernateTemplate; import com.concretepage.persistence.User; public class AppTest { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class); ctx.refresh(); HibernateTemplate hibtemp= ctx.getBean(HibernateTemplate.class); User u1= new User(1,"Ankita"); hibtemp.persist(u1); User u2= new User(2,"Renu"); hibtemp.save(u2); } }
package com.concretepage.persistence; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class User implements Serializable { private static final long serialVersionUID = 1L; @Id private int id; private String name; public User(){ } public User(int id,String name){ this.id=id; this.name=name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }