Massimo Massimo - 15 days ago 5
Java Question

Spring+JPA EntityManager injected in service and dao

I'm working with Spring + JPA (with hibernate as JPA provider) using services and 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.

The dao is
@Autowired
in the service and the
EntityManager
is injected both in Service and Dao, with
@Autowired
.

In this way am I guaranteed to inject the same
EntityManager
both in the Service and in the dao ?

Answer

You can inject EntityManager using @PersistenceContext which will inject shared EntityManager managed by Spring. But i think you should reconsider your approach of having EM in service class as well.

Also look here : Doc

As OP's comments updating : you can have EntityManager only in DAO classes but make those to-be atominc dao calls in same service method and make it transactional.Check out Two Dao atomic calls