Is a Spring Data (JPA) Repository thread-safe? (aka is SimpleJpaRepository thread safe)

12,627

Solution 1

Generally, yes. It's assuming a managed EntityManager which we'll either obtain from Spring's factory classes (in case you're using Spring as container) or as a CDI managed bean (declared through an @Producer method).

Solution 2

Generally Spring wired objects are thread safe.

Here are some helpful links:

http://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-two-crud/

Make sure you use the correct Transaction manager with it

http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/transaction/jta/JtaTransactionManager.html

Share:
12,627
Greg Kopff
Author by

Greg Kopff

Updated on July 25, 2022

Comments

  • Greg Kopff
    Greg Kopff almost 2 years

    I am using a Spring Data (JPA) repository to take care of CRUD boilerplate.

    I define my repository interface like so:

    import org.springframework.data.repository.CrudRepository;
    
    public interface FooRepository extends CrudRepository<Foo, Long>
    {
      public Foo findByXAndYAndZ(X x, Y y, Z z);
    }
    

    Spring then auto-magically generates me an implementation of said interface. What we get back is a proxy, but I believe that eventually we get down to a org.springframework.data.jpa.repository.support.SimpleJpaRepository.

    A JdkDynamicAopProxy is thread-safe if the underlying target class is thread-safe. The question therefore is: is SimpleJpaRepository thread safe?

  • Greg Kopff
    Greg Kopff about 11 years
    Hi Tim - I didn't find anything about thread safety in that article. Did I miss it?
  • Greg Kopff
    Greg Kopff about 11 years
    Hi Oliver - thanks for this. Can I ask though - is this documented somewhere? Do you have any references?
  • Greg Kopff
    Greg Kopff about 11 years
    Can you elaborate on why this "managed" EntityManager makes SimpleJpaRepository thread safe?
  • norgence
    norgence about 11 years
    I'd argue this is a simple consequence from the way an EntityManager is specified to behave in JPA. It is not thread safe by default, thus it needs to be managed (read: correctly bound to a thread and proxied to point to the thread-bound instance). In Spring this is achieved through the use of a SharedEntityManagerCreator. In the CDI case, the container will do that for you.
  • Chrisma Andhika
    Chrisma Andhika over 10 years
    what do you mean by "Spring wired objects"? If I creates a class and define a bean of that class in web app context, than that bean is a singleton by default that is not thread safe. I should handle the thread safety for that bean by myself, Spring won't manage thread safety for the bean even it is wired.
  • Shantanu Wagh
    Shantanu Wagh almost 9 years
    Oliver, do you have an example of using the SharedEntityManagerCreator like you suggest?