简体   繁体   中英

Is javax.persistence.EntityManager thread safe

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM