Spring @Transactional只读

时间:2017-06-12 09:46:52

标签: java spring hibernate spring-boot spring-data-jpa

我有一个基本的SpringBoot应用程序。使用Spring Initializer,嵌入式Tomcat,Thymeleaf模板引擎和包作为可执行的JAR文件

有了这种依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

我创建了这个声明为readOnly的服务:

@Service
@Transactional(readOnly = true)
public class TimeLapseService {

    @Autowired
    TimeLapseRepository timeLapseRepository;

    public Set<TimeLapse> findAllByCompanyId(long companyId) {
        return timeLapseRepository.findAllByCompanyId(companyId);
    }

    public Iterable<TimeLapse> findAll (User user) {

        if (user.isAdmin()) {
            return timeLapseRepository.findAll();
        } else {
            return timeLapseRepository.findAllByCompanyId(user.getCompany().getId());
        }   

    }

    public void createTimeLapse (TimeLapse timeLapse) {
        timeLapseRepository.save (timeLapse);
    }

}

public interface TimeLapseRepository extends CrudRepository<TimeLapse, Long> {
....
}

据我所知,由于服务被声明为readonly,因此创建新服务不应该向DB保留任何内容,但它会在TABLE中创建一行

timeLapseService.createTimeLapse(timeLapse24h);

JPA属性:

spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
hibernate.dialect=org.hibernate.dialect.H2Dialect

1 个答案:

答案 0 :(得分:5)

  

BeanS调用transactional =只读Bean1,它执行查找和   调用transactional =读写Bean2,它保存一个新对象。

> Bean1 starts a read-only tx. 31 09:39:44.199 [pool-1-thread-1] DEBUG
> o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name
> [nz.co.vodafone.wcim.business.Bean1.startSomething]:
> PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''

> 
> Bean 2 pariticipates in it. 31 09:39:44.230 [pool-1-thread-1] DEBUG
> o.s.orm.jpa.JpaTransactionManager - Participating in existing
> transaction
> 
  

没有任何内容提交给数据库。

     

现在更改要添加的Bean2 @Transactional注释   传播= Propagation.REQUIRES_NEW

> Bean1 starts a read-only tx. 31 09:31:36.418 [pool-1-thread-1] DEBUG
> o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name
> [nz.co.vodafone.wcim.business.Bean1.startSomething]:
> PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
> 
> Bean2 starts a new read-write tx 31 09:31:36.449 [pool-1-thread-1]
> DEBUG o.s.orm.jpa.JpaTransactionManager - Suspending current
> transaction, creating new transaction with name

除非您按照以下方式进行,否则将保留

    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void createTimeLapse (TimeLapse timeLapse)
   { 
    timeLapseRepository.save (timeLapse); 
   }