0

I’m using EntityManager in may Dao layer without @PersistenceContext but Dao method is calling service method which is marked as @Transactional. My question is should I use EntityManagerFactory in dao layer and every time get EntityManager to keep thread safety or it’s handled already?

Dao layer:

@RequiredArgsConstructor
public class UserDaoImpl {

 private final EntityManager em;

 public void save(User user){
     em.persist(user);
 }
}

Service layer:

@RequiredArgsConstructor
public class UserService {

 private final UserDao userDao;

 @Transactional
 public void save(User user) {
   userDao.save(user);
 }
}

Tnx!

Eugen Labun
  • 2,561
  • 1
  • 22
  • 18
Arman Tumanyan
  • 386
  • 3
  • 14

2 Answers2

1

just add @PersistenceContext to your Entity Manager and the container will handle it for you, but if you are not in JEE environment so create your own entity manager factory, but I think in your current case the entity manager will still null. Also you must create you persistence unit XML file, and take attention in transaction-type, it must be JTA if you use @PersistenceContext and it should be RESSOURCE_LOCAL if you will create your own Entity Manager Factory.

Ismail
  • 2,322
  • 1
  • 12
  • 26
  • I’m using Spring Boot 2+ and it’s working correctly, just wanted to make sure if it’s thread safe in my case or I need to add @PersistenceContext on it. – Arman Tumanyan Mar 28 '19 at 09:21
  • If you are using Spring Boot so you don't need @PersistenceContext. – Ismail Mar 28 '19 at 09:23
  • So Spring Boot will handle everything? – Arman Tumanyan Mar 28 '19 at 09:25
  • I think yes because you are already using @Transactional, so spring will handle transactions for you, take a look at this: https://dzone.com/articles/how-does-spring-transactional – Ismail Mar 28 '19 at 09:29
0

This stackoverflow question Is EntityManager really thread-safe? already got answer to your question.

And this one "Future-Proofing Java Data Access - DAO Pattern Done Right" shows how to design DAO layer.

But if you are using Spring and Spring Data repository then I would suggest defining repository using CrusRepository or JpaRepository interface. That would offload your concerns regarding EntityManager handling to Spring.

ImTiaZ
  • 11
  • 4