Java Reference
In-Depth Information
To enable declarative transaction management for the methods annotated with @Transactional ,
you have to enable the <tx:annotation-driven> element in your bean configuration file. By default,
it will look for a transaction manager with the name transactionManager , so you have to declare
a HibernateTransactionManager instance with that name. HibernateTransactionManager requires
the session factory property to be set. It will manage transactions for sessions opened through this
session factory.
Similarly, you can simplify the JpaCourseDao class as follows with the help of Spring's JpaTemplate .
You also declare all the DAO methods to be transactional.
package com.apress.springenterpriserecipes.course.jpa;
...
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.transaction.annotation.Transactional;
public class JpaCourseDao implements CourseDao {
private JpaTemplate jpaTemplate;
public void setJpaTemplate(JpaTemplate jpaTemplate) {
this.jpaTemplate = jpaTemplate;
}
@Transactional
public void store(Course course) {
jpaTemplate.merge(course);
}
@Transactional
public void delete(Long courseId) {
Course course = jpaTemplate.find(Course.class, courseId);
jpaTemplate.remove(course);
}
@Transactional(readOnly = true)
public Course findById(Long courseId) {
return jpaTemplate.find(Course.class, courseId);
}
@Transactional(readOnly = true)
public List<Course> findAll() {
return jpaTemplate.find("from Course");
}
}
In the bean configuration file for JPA (i.e., beans-jpa.xml ), you can declare a JpaTemplate instance
and inject it into all JPA DAOs. Also, you have to declare a JpaTransactionManager instance for managing
JPA transactions.
<beans xmlns=" http://www.springframework.org/schema/beans"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx=" http://www.springframework.org/schema/tx"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Search WWH ::




Custom Search