Announcement Announcement Module
No announcement yet.
Spring Data JPA: how can I share JpaRepository among threads? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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.

  • #2
    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 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.



    • #3
      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.