Spring+Hibernate Transaction Management
In continuation to my previous post, we will see how Spring manages the Hibernate session context with the help of @Transactional annotation
@Transactional
public void addUser(){
Session session = sessionFactory.getCurrentSession();
//add user code goes here
session.save(user);
}
@Transactional annotation in spring is applied to the service methods to execute the code inside the method as a single transaction. When we are plugging in Spring with hibernate. This method code runs in a single Hibernate session.
The Scope and Context of the Hibernate session Context in @Transactional annotation is given below.
Scope - Creates a new session when method starts, close the session when method ends.
Context - There will be only 1 session created inside the body @Transactional annotated method. The same session will be re-issued on calling getCurrentSession() again inside the same method. So, the context is @Transactional method here.
In a way, the hibernate session is controlled by Spring transaction here.
@Transactional
public void addUser(){
Session session = sessionFactory.getCurrentSession();
//add user code goes here
session.save(user);
}
@Transactional annotation in spring is applied to the service methods to execute the code inside the method as a single transaction. When we are plugging in Spring with hibernate. This method code runs in a single Hibernate session.
The Scope and Context of the Hibernate session Context in @Transactional annotation is given below.
Scope - Creates a new session when method starts, close the session when method ends.
Context - There will be only 1 session created inside the body @Transactional annotated method. The same session will be re-issued on calling getCurrentSession() again inside the same method. So, the context is @Transactional method here.
Comments
Post a Comment