[英]Spring+JPA EntityManager injected in service and dao
I'm working with Spring + JPA (with hibernate as JPA provider) using services and dao. 我正在使用Spring + JPA (使用Hibernate作为JPA提供程序)使用服务和dao。
I'd like to inject the JPA EntityManager
in both service and dao, with the service managing the transactions and the dao managing the object persistence. 我想在服务和dao中注入JPA
EntityManager
,其中服务管理事务,而dao管理对象持久性。
The dao is @Autowired
in the service and the EntityManager
is injected both in Service and Dao, with @Autowired
. dao在服务中是
@Autowired
,而EntityManager
在服务和Dao中都使用@Autowired
注入。
In this way am I guaranteed to inject the same EntityManager
both in the Service and in the dao ? 这样我是否可以保证在Service和dao中都注入相同的
EntityManager
?
You can inject EntityManager using @PersistenceContext which will inject shared EntityManager managed by Spring. 您可以使用@PersistenceContext注入EntityManager,这将注入由Spring管理的共享EntityManager。 But i think you should reconsider your approach of having EM in service class as well.
但是我认为您也应该重新考虑在服务级别中使用EM的方法。
Also look here : Doc 也请看这里: Doc
As OP's comments updating : you can have EntityManager only in DAO classes but make those to-be atomic dao calls in same service method and make it transactional. 随着OP的注释更新:您只能在DAO类中拥有EntityManager,但是可以在相同的服务方法中进行那些将成为原子dao的调用,并使它具有事务性。 Check out Two Dao atomic calls
查看两个Dao原子调用
EntityManager is initialized as a Singleton bean and so you don't have to worry as long as you make sure you wire the correct EntityManager bean in case when you have 2 or more configured in your application . EntityManager初始化为Singleton Bean,因此只要确保在应用程序中配置了2个或更多的情况下连接正确的EntityManager Bean,就不必担心。
@PersistenceContext(unitName = "<persistent-unit-name>")
private EntityManager entityManager;
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="persistenceUnitName" value="<persistent-unit-name>" />
...
</bean>
Its totally wrong way but, all your EntityManager Instances will create with EntityManagerFactoryBean. 这是完全错误的方式,但是,所有EntityManager实例都将使用EntityManagerFactoryBean创建。 If you have created this @Bean, it doesn't guarantee you have the same instance of EntityManager .
如果创建了此@Bean,则不能保证您具有相同的EntityManager实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.