Reputation: 426
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!
Upvotes: 0
Views: 1481
Reputation: 11
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.
Upvotes: 0
Reputation: 3022
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.
Upvotes: 1