首页 > 解决方案 > JDBC Spring数据@Transactional不起作用

问题描述

我正在使用 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);
    }
}

我希望在调用RecordClient'方法时不会向 db 插入任何记录,因为' throws 。而是添加了记录。insert()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;
    }
}

标签: javaspringspring-data

解决方案


您必须注入datasource而不是手动创建它。我猜是因为@Transactional仅适用于 Spring 托管 bean。如果您通过调用new构造函数(如 this 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();
  }
}

推荐阅读