1

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 ?

Massimo Petrus
  • 1,881
  • 2
  • 13
  • 26
  • @shazin : how can you configure JPA EntityManager bean to be singleton or prototype ? – Goro Nov 23 '16 at 09:31

4 Answers4

4

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 atomic dao calls in same service method and make it transactional. Check out Two Dao atomic calls

Goro
  • 516
  • 4
  • 15
  • The point is that I have let's say one dao or more which are in charge to persist my entities. I need a service which handle the transaction. If I do it in the daos I could have dirty transactions in case of errors. How can I manage it otherwise ? – Massimo Petrus Nov 23 '16 at 10:03
  • @Massimo 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 http://stackoverflow.com/questions/3886909/where-should-transactional-be-place-service-layer-or-dao – Goro Nov 23 '16 at 10:15
  • Thanks it's what I need, please update your answer so I will mark as solution – Massimo Petrus Nov 23 '16 at 10:21
1

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 .

    @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>
Sagar
  • 818
  • 1
  • 6
  • 13
0

Have you tried @PersistenceContext annotation

@PersistenceContext
private EntityManager entityManager;

Take a look at this link for more info. Also look here for all the possible options you have with this annotation.

Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
0

Its totally wrong way but, all your EntityManager Instances will create with EntityManagerFactoryBean. If you have created this @Bean, it doesn't guarantee you have the same instance of EntityManager .

Pasha
  • 1,534
  • 15
  • 27