領先一步
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 定義。