领先一步
VMware 提供培训和认证,助您加速进步。
了解更多Spring 2.0 增加了对 JPA 数据访问标准的支持,并提供了所有您期望的标准 Spring 支持类。Mark Fisher 发布了一篇关于如何在 Spring 2.0 中使用此新支持的精彩博文。然而,我们经常收到的一个问题是,为什么有人会想使用 Spring 类(JpaTemplate)来访问 EntityManager。这个问题的最佳答案在于 JpaTemplate 提供的增值功能。除了提供 Spring 数据访问的标志性单行便利方法外,它还提供了自动参与事务和将 PersistenceException 转换为 Spring DataAccessException 层次结构的功能。
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
JpaTransactionManager 负责创建 EntityManager、开启事务并将其绑定到当前线程上下文。 <tx:annotation-driven /> 只是告诉 Spring 将事务性建议应用于任何带有 @Transactional 注释的类或方法。您现在可以只编写您的主线 DAO 逻辑,而无需担心事务语义。
public Collection loadProductsByCategory(String category) {
return entityManager.createQuery("from Product p where p.category = :category")
.setParameter("category", category).getResultList();
}
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
public class ProductDaoImpl implements ProductDao {
private EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this. entityManager = entityManager;
}
public Collection loadProductsByCategory(String category) {
return entityManager.createQuery("from Product p where p.category = :category")
.setParameter("category", category).getResultList();
}
}
通过添加一个 bean 定义,Spring 容器将充当 JPA 容器,并从您的 EntityManagerFactory 注入一个 EntityManager。
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
@Repository
public class ProductDaoImpl implements ProductDao {
private EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this. entityManager = entityManager;
}
public Collection loadProductsByCategory(String category) {
return entityManager.createQuery("from Product p where p.category = :category")
.setParameter("category", category).getResultList();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" />
<bean id="productDaoImpl" class="product.ProductDaoImpl"/>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>
就这样。两个注解和四个 bean 定义。