We are designing an application using Spring-Hibernate where 6 threads run simultaneously. Each thread performs a different operation and inserts/updates a few records in common table(all threads work on common tables).
While we know that we can have just one single instance of EntityManagerFactory
, we are not sure how many instances of EntityManager
should we have? Should we create six entity managers(one for each thread)? How should we create the DAO? Should we just create one EntityManager
like following and use the same dao class for all the threads? I know EM specification says that it's not thread safe, but I read somewhere that injected EM in the case of spring are threadsafe(I wasn't convinced with the explanation, though).
@Trasactional
public class myAppDao {
@PersistenceContext
private EntityManager entityManager;
..
}
or should we do something different ?
Hibernate provides implementation of JPA interfaces EntityManagerFactory and EntityManager . EntityManagerFactory provides instances of EntityManager for connecting to same database. All the instances are configured to use the same setting as defined by the default implementation.
5.1. An entity manager is not thread-safe.
EntityManagerFactory instances are heavyweight objects. Each factory might maintain a metadata cache, object state cache, EntityManager pool, connection pool, and more. If your application no longer needs an EntityManagerFactory , you should close it to free these resources.
The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit.
Yes, usually the EntityManager
or Session
are bound to the thread (implemented as a ThreadLocal variable). @PersistenceContext
annotation is recognized by Spring IoC/CDI and is treated in a special way to enable this.
There is some layer in your app (usually marked as @Transactional
) that creates EntityManager and binds it to the ThreadLocal variable. This happens every time the 1st @Transactional
is invoked. And same - EntityManager
is closed every time the method exits.
Alternatively this can be implemented using OpenSessionInViewInterceptor
or OpenSessionInViewFilter
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With