简体   繁体   English

JDBC Spring 数据 @Transactional 不起作用

[英]JDBC Spring data @Transactional not working

I'm using springboot and spring-data-jdbc.我正在使用 springboot 和 spring-data-jdbc。

I wrote this repository class我写了这个存储库类

@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();
    }
}

Then I wrote a client class that invokes the insert method然后我写了一个调用insert方法的客户端类

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

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

I would expect that no record are insert to db when RecordClient 's insert() method is invoked, because RecordRespository 's insert() throws Exception .我希望在RecordClientinsert()方法时没有记录插入到数据库中,因为RecordRespositoryinsert()抛出Exception Instead the record is added however.而是添加了记录。

What am I missing?我错过了什么?

EDIT.编辑。 This is the class where I configure my Datasource这是我配置数据源的类

@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;
    }
}

You have to inject your datasource instead of creating it manually.您必须注入datasource而不是手动创建它。 I guess because @Transactional only works for Spring managed beans.我猜是因为@Transactional只适用于 Spring 管理的 bean。 If you create a datasource instance by calling new constructor (like this new JDBCConfig(). postgresDataSource() ), you are creating it manually and it's not a Spring managed beans.如果您通过调用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