Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 446
Greg Kopff Avatar asked Apr 12 '13 07:04

Greg Kopff


People also ask

Is Spring JPA repository thread safe?

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.

Is Spring boot is thread safe?

In order to answer that question, you first need to understand when Spring creates a new thread. In a standard servlet-based Spring web application, every new HTTP request generates a new thread. If the container creates a new bean instance just for that particular request, we can say this bean is thread-safe.

Should I use JpaRepository?

JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.

What is Spring boot Repositry?

A repository is a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects. It is a specialization of the @Component annotation allowing for implementation classes to be autodetected through classpath scanning.


2 Answers

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

like image 138
Oliver Drotbohm Avatar answered Nov 15 '22 14:11

Oliver Drotbohm


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

like image 28
Tim Spann Avatar answered Nov 15 '22 12:11

Tim Spann