首页 > 解决方案 > Propagation REQUIRED 如何在 Spring Boot 中工作?

问题描述

我只是想了解 spring 中的事务传播:在我的项目中使用 jpa、postgres、验证器和 web starter。需要传播 说:

logging.level.sql=debug
spring.datasource.generate_unique_name=false

spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=dummy
spring.datasource.password=dummy
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto=update

spring.datasource.hikari.auto-commit=false
spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true
@Slf4j
@Component
@RequiredArgsConstructor
public class AppRunner implements CommandLineRunner {
    private final UserRepository userRepository;

    @Override
    public void run(String... args) throws Exception {
        insertUserBunty();// this transaction should fail but its getting persisted
    }

    @Transactional(propagation = Propagation.REQUIRED)
    void insertUserBunty() {
        User bunty = new User(null, "Bunty");
        userRepository.save(bunty);
        insertUserKumar();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    void insertUserKumar() {
        User kumar = new User(null, "Kumar");
        userRepository.save(kumar);
        throw new RuntimeException("This will rollback both insert Bunty and Kumar");
    }
}

标签: javaspringspring-boothibernatejpa

解决方案


原因是@Transactional当您从类中的另一个方法调用该方法时,它不起作用。原因是 Spring 处理事务特性的方式。它基本上由您的类的代理处理,因此@Transactional注释仅在您的类外的方法调用该方法时才有效。在以下位置查看详细信息:


推荐阅读