Massimo Massimo - 6 months ago 47
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

in both service and dao, with the service managing the transactions and the dao managing the object persistence.

The dao is
in the service and the
is injected both in Service and Dao, with

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


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