2010-03-10 272 views
36

我有幾個關於在Tomcat上運行的JPA + Spring集成的問題。我一直在尋找一些時間,一直沒有找到具體的答案,所以這裏有:如何使用spring注入JPA EntityManager

是否有可能讓Spring將JPA entityManager對象注入到我的DAO類中而不擴展JpaDaoSupport?如果是,Spring是否在這種情況下管理交易?

我想保持我的Spring配置儘可能地簡單:

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> 
    <property name="entityManagerFactory" ref="em"/> 
</bean> 
<bean id="em" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> 
    <property name="persistenceUnitName" value="myPU"/> 
</bean> 

編輯:這是非常有益的,謝謝大家!

回答

29

是的,雖然它充滿了疑難雜症,但由於JPA有點奇怪。這是非常值得一讀的注入JPA EntityManagerEntityManagerFactory的文檔,而無需在代碼中明確Spring的依賴:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

這可以讓你無論是注入EntityManagerFactory,否則注入線程安全的,事務代理的直接EntityManager。後者使代碼更簡單,但意味着需要更多的Spring管道。

12

是否有可能有彈簧注入JPA entityManager對象到我的DAO類中,但沒有擴展JpaDaoSupport?如果是的話,春天是否在這種情況下管理交易?

這在12.6.3. Implementing DAOs based on plain JPA記錄黑白色:

,能夠編寫針對 平原JPA碼而不使用任何彈簧 依賴關係,使用一個注入 EntityManagerFactoryEntityManager。 注意Spring能夠識別字段或者方法級別 @PersistenceUnit@PersistenceContext註釋都 如果啓用了 PersistenceAnnotationBeanPostProcessor 。一個相應的DAO實現 可能是這樣的(...)

以及有關的事務管理,看看12.7. Transaction Management

春天JPA允許配置JpaTransactionManager暴露一個JPA事務JDBC訪問相同JDBC數據源的代碼,前提是已註冊的JpaDialect支持檢索基礎JDBC連接。開箱即用,Spring爲Toplink,Hibernate和OpenJPA JPA實現提供了方言。有關JpaDialect機制的詳細信息,請參閱下一節。

3

最新的Spring + JPA版本從根本上解決了這個問題。 您可以瞭解更多如何使用Spring和JPA togather在a separate thread