In a computation involving an @Entity
instance, one thread A creates a new thread B. Thread A holds a reference to the entity and passes this reference over to thread B.
Thread A takes care of serving a single HTTP request, finding the entity inside a repository, and sending an HTTP response.
Thread B takes care of some long-running computation involving that entity.
Q: Why did I choose two threads? A: I don't want a long-running HTTP request-response cycle; instead I want to have a fast HTTP request-response cycle that quickly responses "Computation started" to my user.
Accessing the entity from thread A works flawlessy.
But accessing the entity from thread B doesn't work: the moment I try to access an entity relationship (which should lazily fetch data from Hibernate), I get the exception org.hibernate.LazyInitializationException: could not initialize proxy - no Session
.
Is a JPA/Hibernate session scoped to a single thread - namely the thread creating that session (thread A in my case, as this is the thread querying my repository for the entity)? If this is the case, how can I make several threads share a Hibernate session so that I can work with the same entity from several threads?
Changing my entity's relashionship behavior to "eager loading" is not a viable solution. I'm also looking for a solution that is non-intrusive to my domain classes / entities (e.g. I don't want to use a PersistenceContext
or EntityManager
inside my domain classes to re-attach detached entities.