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?
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.
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.
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.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With