Example of @EnableTransactionManagement in Spring

March 21, 2013
In spring , when we are using @Configuration i.e XML free configuration and need to connect to database with hibernate. We need to use @EnableTransactionManagement. This is applied on class level.
@Configuration
@EnableTransactionManagement
public class AppConfig {}
 
We need to create bean for HibernateTemplate and sessionFactory and HibernateTransactionManager. Find the example below. 

AppConfig.java
package 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());
	}
}
 


AppTest.java
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);
			
	}
}
 


User.java
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;
  } 
} 
 




Posted by linuxism
,