gpt4 book ai didi

java - Spring @Transactional 只读

转载 作者:行者123 更新时间:2023-11-29 07:29:46 25 4
gpt4 key购买 nike

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

有了这个依赖

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

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

@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> {
....
}

据我所知,由于该服务被声明为只读,因此创建一个新服务不应将任何内容持久保存到数据库,但它会在表中创建一行

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

最佳答案

BeanS call a transactional=read-only Bean1, which does a lookup and calls transactional=read-write Bean2 which saves a new object.

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

Nothing is committed to the database.

Now change Bean2 @Transactional annotation to add propagation=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);
}

关于java - Spring @Transactional 只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44496333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com