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