Is a Spring Data (JPA) Repository thread-safe? (aka is SimpleJpaRepository thread safe)
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
Greg Kopff
Updated on July 25, 2022Comments
-
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: isSimpleJpaRepository
thread safe? -
Greg Kopff about 11 yearsHi Tim - I didn't find anything about thread safety in that article. Did I miss it?
-
Greg Kopff about 11 yearsHi Oliver - thanks for this. Can I ask though - is this documented somewhere? Do you have any references?
-
Greg Kopff about 11 yearsCan you elaborate on why this "managed"
EntityManager
makesSimpleJpaRepository
thread safe? -
norgence about 11 yearsI'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 aSharedEntityManagerCreator
. In the CDI case, the container will do that for you. -
Chrisma Andhika over 10 yearswhat 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 almost 9 yearsOliver, do you have an example of using the SharedEntityManagerCreator like you suggest?