Massimo Massimo - 1 year ago 96
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 ?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download