Is a Spring Data (JPA) Repository thread-safe? (ak

2020-03-18 03:18发布

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?

3条回答
smile是对你的礼貌
2楼-- · 2020-03-18 03:43

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

查看更多
Deceive 欺骗
3楼-- · 2020-03-18 03:43

I'm not positive yet, I could totally be wrong, but I don't think repositories are thread safe IN SPECIFIC CASES. Take a look at:

RepositoryFactorySupport.QueryExecutorMethodInterceptor in spring-data-commons on github.

There is a concurrent hashmap containing methods -> queries. If those queries contain state, or any properties of those queries contain state, then the repository is no longer thread safe. A good example would be spring-data-neo4j. DerivedGraphRepositoryQuery specifically has issues since it contains CypherFinderQuery's. THOSE contain state in the form of parameters to the queries. I BELIEVE it's possible to have a race condition where a parameter is overwritten by another thread during a query in DerivedGraphRepository. This could happen in other spring data repositories if the authors of the query objects give them state.

查看更多
登录 后发表回答