based on this example :
@Service
public class Purchase {
@PersistenceContext
private EntityManager em;
@Autowired
private PurchaseDAO dao;
private String normalField;
.... // methods, operations, etc
}
Please help correct me if im mistaken :
- The service class Purchase and the PurchaseDAO are singletons that are managed by spring
- The service class's field normalField is not threadsafe, because singleton is a single object shared by many
- Let's assume the @Repository-annotated-PurchaseDAO doesnt have any field, which means it's threadsafe, will be injected automatically by spring
- The EntityManager instance is also a threadsafe property because @PersistenceContext will make sure that the entityManager of the current transaction will be used.
Thank you !
Best Answer
SpringSource forums: I have been looking for answers to the same question on the forum... The general concensus seems to be that while EntityManager is not thread safe per JPA specs, the EntityManager injected by Spring through its EntityManager proxy may be.
Hibernate: An EntityManager is an inexpensive, non-threadsafe object that should be used once, for a single business process, a single unit of work, and then discarded. An EntityManager will not obtain a JDBC Connection (or a Datasource) unless it is needed, so you may safely open and close an EntityManager even if you are not sure that data access will be needed to serve a particular request.