领先一步
VMware 提供培训和认证,以加速您的进步。
了解更多Spring 2.0 增加了对 JPA 数据访问标准的支持,包含了所有预期的标准 Spring 支持类。 Mark Fisher 有一篇很棒的帖子,介绍了如何使用这种新的支持。然而,我们一直被问到的一个问题是,为什么有人会想要使用 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 中注入一个 EnitityManager。
<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 定义。