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