Spring Data JPA事务支持

一 点睛

Spring Data JPA对所有默认方法都开启了事务支持,且查询类事务默认启用readOnly=true属性。

二 SimpleJpaRepository缩减版源码

@Repository
@Transactional(readOnly = true)
public class SimpleJpaRepositoryextends Serializable> implements JpaRepository,
        JpaSpecificationExecutor {
    ......
    @Transactional
    public void delete(ID id) {
    ......
    }
 
    @Transactional
    public void delete(T entity) {
    ......
    }
 
 
    @Transactional
    public void delete(Iterableextends T> entities) {
    ......
    }
 
 
    @Transactional
    public void deleteInBatch(Iterable entities) {
    ......
    }
 
 
    @Transactional
    public void deleteAll() {
    ......
    }
 
 
    @Transactional
    public void deleteAllInBatch() {
    ......
    }
 
 
    public T findOne(ID id) {
    ......
    }
 
 
    protected Map getQueryHints() {
    ......
    }
 
    private JpaEntityGraph getEntityGraph() {
    ......
    }
 
 
    @Override
    public T getOne(ID id) {
    ......
    }
 
 
    public boolean exists(ID id) {
    ......
    }
 
 
    public List findAll() {
    ......
    }
 
 
    public List findAll(Iterable ids) {
    ......
    }
 
 
    public List findAll(Sort sort) {
    ......
    }
 
 
    public Page findAll(Pageable pageable) {
    ......
    }
 
 
    public T findOne(Specification spec) {
    ......
    }
 
 
    public List findAll(Specification spec) {
    ......
    }
 
 
    public Page findAll(Specification spec, Pageable pageable) {
    ......
    }
 
 
    public List findAll(Specification spec, Sort sort) {
    ......
    }
 
 
    public long count() {
    ......
    }
 
 
    public long count(Specification spec) {
 
    ......
    }
 
 
    @Transactional
    public extends T> S save(S entity) {
    ......
    }
 
 
    @Transactional
    public extends T> S saveAndFlush(S entity) {
    ......
    }
 
    @Transactional
    public extends T> List save(Iterable entities) {
    ......
    }
 
    ......
}

三 源码分析

从源码分析可以看出,SimpleJpaRepository在类级别定义了@Transactional(readOnly = true),而在和save、delete相关的操作重写了@Transactional属性,此时readOnly属性是false,其余查询操作readOnly仍然为true。

你可能感兴趣的:(Spring Data JPA事务支持)