Feb 18th, 2013, 09:41 AM
Spring Data JPA: how can I share JpaRepository among threads?
I have a Spring Data Jpa "JpaRepository" for my @Entity. Using it in a single-threaded environment works great (e.g. using the JpaRepository singleton in a simple JUnit test; e.g. using the JpaRepository singleton from the thread that was created by the HTTP request to my Spring MVC controller).
The moment that I want to use the JpaRepository from two or more threads, everything breaks: I get LazyInitializationExceptions when accessing an entity's relationships, JPA persistence contexts (... or Hibernate sessions) are non-existing, etc. pp.
How can I use a JpaRepository from two or more threads?
Notice broadly speaking, data integrity is not a huge priority for me. I don't care about problems with data integrity with respect to transaction management. I just want multithreading JpaRepository access to work at all!
Also notice that in my current understanding, sticking to single-threaded JpaRepository access is not a solution: my web application shall be "fast" for users. For this I have implemented a "stream of data" being loaded to the HTML page. (comparable to inifinite scrolling at Facebook and Pinterest; exploiting XmlHttpRequest). So while a user is browsing the HTML page, additional data gets loaded from my web application. For this data to exist, I am accessing a data queue on my server. This data queue is filled by some "background thread" with data coming from a JpaRepository.
Feb 19th, 2013, 10:48 PM
You can change lazy mode to eagar to solve LazyInitializationExceptions. For objects with lazy=true,proxy is returned.once you access the object property then only the database call is made.so If you access object outside the persistence context,it will throw LazyInitializationExceptions as it is trying to hit database when there is no persistence context attached.
And also look at this thread.
Hope this will help you.
Feb 20th, 2013, 06:03 AM
Thanks Vaijesh! But in my particular case, eager-loading won't help: My data has a graph structure (think of my @Entity class representing a social network). By recursion, eagerly loading could possibly load thousands of interconnected entities.