如何使用Spring注入JPA EntityManager [英] How to inject JPA EntityManager using spring

查看:251
本文介绍了如何使用Spring注入JPA EntityManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让 Spring 在不扩展JpaDaoSupport的情况下将JPA entityManager对象注入到我的DAO类中?如果是,在这种情况下,Spring是否管理交易?

Is it possible to have Spring inject the JPA entityManager object into my DAO class without extending JpaDaoSupport? If yes, does Spring manage the transaction in this case?

我试图使我的Spring配置尽可能简单:

I'm trying to keep my Spring configuration as simple as possible:

<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>

推荐答案

是的,尽管充满了陷阱,因为JPA有点特殊.非常值得阅读有关注入JPA EntityManagerEntityManagerFactory的文档,而在您的代码中没有明确的Spring依赖项:

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

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

这允许您要么注入EntityManagerFactory,要么直接注入EntityManager的线程安全的事务代理.后者使代码更简单,但意味着需要更多的Spring Pipe.

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

这篇关于如何使用Spring注入JPA EntityManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆