Commit on jdbcTemplate or DataSource

后端 未结 5 747
天命终不由人
天命终不由人 2021-02-02 14:31

I wanted to do commit and rollback using jdbcTemplate.

My question is based on this thread

How do I commit or rollback, should I do it on jdbcTemplate like

5条回答
  •  时光取名叫无心
    2021-02-02 15:28

    Use @Transactional. But of course, before of that, you will have to create bean definition for DataSourceTransactionManager:

    // Your DataSource bean definition
    @Bean
    public DataSource dataSource() {
        ....
    }
    
    // Transaction manager bean definition
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
    
        return dataSourceTransactionManager;
    }
    

    And then you can use @Transactional. Example of service:

    @Service
    public class MyServiceImpl {
    
        @Autowired
        private MyDAO myDAO;
    
        @Transactional
        public void insert(Entity entity) {
           myDAO.insert(entity);
        }
    }
    

提交回复
热议问题