---
title: "spring2中jpa的配置和使用"
author: "swingfly"
date: "2009-06-03T02:11:41Z"
tags: []
slug: "spring2-jpa"
draft: false
lastmod: "2009-06-03T02:11:41Z"
id: 400668
url: "https://swingfly.iteye.com/blog/400668"
---

配置JPA  
Spring JPA提供了两种方法创建JPA EntityManagerFactory  
&lt;beans&gt;  
    &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"&gt;  
        &lt;property name="persistenceUnitName" value="myPersistenceUnit" /&gt;  
    &lt;/bean&gt;  
&lt;/beans&gt;  
FactoryBean 创建的EntityManagerFactory适用于仅通过JPA进行数据访问的环境。由于使用了PersistenceProvider自动侦测机 制，所以只能从默认路径classpath:META-INF/persistence.xml中读取配置信息。

&lt;beans&gt;  
    &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt;  
        &lt;property name="dataSource" ref="someDataSource" /&gt;  
        &lt;property name="loadTimeWeaver"&gt;  
            &lt;bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver" /&gt;  
        &lt;/property&gt;  
    &lt;/bean&gt;  
&lt;/beans&gt;  
FactoryBean 提供了对JPA EntityManagerFactory的完整控制，非常适合那种有简单定制需要的环境。你可以处理多个persistence.xml配置文件；覆盖 persistence.xml文件的默认路径；可以传递Spring托管的JDBC DataSource给JPA PersistenceProvider，用来替代persistence.xml中的JDBC配置(这个Spring托管的DataSource通常被 作为nonJtaDataSource传送给PersistenceProvider，并且覆盖persistence.xml中相同的 nonJtaDataSource)。

数据访问  
基于JPA的DAO可以通过三种方式进行数据访问JpaDaoSupport，JpaTemplate和plain JPA。其中JpaTemplate是plain JPA的封装，而JpaDaoSupport又是JpaTemplate的封装。无疑，使用不对Spring产生任何依赖的Plain JPA的API进行编程是最好选择。  
public class ProductDaoImpl implements ProductDao {  
    private EntityManager entityManager = null;

    @PersistenceContext  
    public void setEntityManager(EntityManager entityManager) {  
        this.entityManager = entityManager;  
    }

    public Collection loadProductsByCategory(String category) {

         EntityManager em= entityManagerFactory.createEntityManager();  
         Query query = em.createQuery("from Product as p where p.category = :category");  
         query.setParameter("category", category);  
         return query.getResultList();  
    }  
}  
注意，必须激活PersistenceAnnotationBeanPostProcessor功能才能让Spring识别@PersistenceContext注解。  
&lt;beans&gt;  
    &lt;!-- JPA annotations bean post processor --&gt;  
    &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/&gt;

    &lt;bean id="myProductDao" class="product.ProductDaoImpl" /&gt;  
&lt;/beans&gt;

异常转化  
Spring提供了一个允许通过使用@Repository注解进行透明的异常转化的解决方案。  
@Repository  
public class ProductDaoImpl implements ProductDao {  
    ...  
}

&lt;beans&gt;  
    &lt;!-- Exception translation bean post processor --&gt;  
    &lt;bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /&gt;

    &lt;bean id="myProductDao" class="product.ProductDaoImpl" /&gt;  
&lt;/beans&gt;  
后置处理器将自动的寻找所有的异常转化器(PersistenceExceptionTranslator这个接口的实现类)并通知所有打上@Repository注解的bean，从而能够使得被找到的异常转化器能够在抛出异常时做相应的异常转化工作。

总结来说：DAO能够基于普通的Java持久层API和注解来实现，但同样也能享受到由Spring管理事务、IoC和透明的异常转化(转化成为Spring的异常体系)等好处。