繁体   English   中英

JDBC Spring 数据 @Transactional 不起作用

[英]JDBC Spring data @Transactional not working

我正在使用 springboot 和 spring-data-jdbc。

我写了这个存储库类

@Repository
@Transactional(rollbackFor = Exception.class)
public class RecordRepository {
    public RecordRepository() {}

    public void insert(Record record) throws Exception {
        JDBCConfig jdbcConfig = new JDBCConfig();
        SimpleJdbcInsert messageInsert = new SimpleJdbcInsert(jdbcConfig.postgresDataSource());

        messageInsert.withTableName(record.tableName()).execute(record.content());
        throw new Exception();
    }
}

然后我写了一个调用insert方法的客户端类

@EnableJdbcRepositories()
@Configuration
public class RecordClient {
    @Autowired
    private RecordRepository repository;

    public void insert(Record r) throws Exception {
        repository.insert(r);
    }
}

我希望在RecordClientinsert()方法时没有记录插入到数据库中,因为RecordRespositoryinsert()抛出Exception 而是添加了记录。

我错过了什么?

编辑。 这是我配置数据源的类

@Configuration
@EnableTransactionManagement
public class JDBCConfig {

    @Bean
    public DataSource postgresDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/db");
        dataSource.setUsername("postgres");
        dataSource.setPassword("root");

        return dataSource;
    }
}

您必须注入datasource而不是手动创建它。 我猜是因为@Transactional只适用于 Spring 管理的 bean。 如果您通过调用new构造函数(例如new JDBCConfig(). postgresDataSource() )创建数据源实例,则您是手动创建它,它不是 Spring 管理的 bean。

@Repository
@Transactional(rollbackFor = Exception.class)
public class RecordRepository {

  @Autowired
  DataSource dataSource;

  public RecordRepository() {}

  public void insert(Record record) throws Exception {
    SimpleJdbcInsert messageInsert = new SimpleJdbcInsert(dataSource);
    messageInsert.withTableName(record.tableName()).execute(record.contents());
    throw new Exception();
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM