How to set autocommit to false in spring jdbc template

前端 未结 7 1861
天命终不由人
天命终不由人 2020-12-08 21:01

Currently I\'m setting autocommit to false in spring through adding a property to a datasource bean id like below :

   

        
7条回答
  •  长情又很酷
    2020-12-08 21:09

    I just came across this and thought the solution would help someone even if it's too late.

    As Yosef said, the connection that you get by calling getJdbcTemplate().getDataSource().getConnection() method may or may not be the one used for the communication with database for your operation.

    Instead, if your requirement is to just test your script, not to commit the data, you can have a Apache Commons DBCP datasource with auto commit set to fault. The bean definition is given below:

    /**
     * A datasource with auto commit set to false.
     */
    @Bean
    public DataSource dbcpDataSource() throws Exception {
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setDefaultAutoCommit(false);
        ds.setEnableAutoCommitOnReturn(false);
        return ds;
    }
    
    // Create either JdbcTemplate or NamedParameterJdbcTemplate as per your needs
    @Bean
    public NamedParameterJdbcTemplate dbcpNamedParameterJdbcTemplate() throws Exception {
        return new NamedParameterJdbcTemplate(dbcpDataSource());
    }
    

    And use this datasource for any such operations.

    If you wish to commit your transactions, I suggest you to have one more bean of the datasource with auto commit set to true which is the default behavior.

    Hope it helps someone!

提交回复
热议问题