Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should there be an EntityManager per thread in Spring-Hibernate?

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 ?

like image 301
bluelurker Avatar asked Feb 06 '17 17:02

bluelurker


People also ask

Does hibernate use EntityManager?

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.

Is JPA EntityManager thread safe?

5.1. An entity manager is not thread-safe.

Do we need to close EntityManager in spring boot?

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.

Why do we need EntityManager in spring boot?

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.


1 Answers

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.

like image 124
Stanislav Bashkyrtsev Avatar answered Oct 06 '22 00:10

Stanislav Bashkyrtsev