How to set autocommit to false in spring jdbc template

前端 未结 7 1828
天命终不由人
天命终不由人 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:27

    You will have to do for each statement that the jdbcTemplate executes. Because for each jdbcTemplate.execute() etc it gets a new connection from the Datasource's connection pool. So you will have to set it for the connection that the connection the jdbcTemplate uses for that query. So you will have to do something like

     jdbcTemplate.execute("(){
    
            @Override
            public  Integer doInPreparedStatement(PreparedStatement stmt) throws SQLException, DataAccessException 
            {
                Connection cxn = stmt.getConnection();
                // set autocommit for that cxn object to false
                cxn.setAutoCommit(false);
                // set parameters etc in the stmt
                ....
                ....
                cxn.commit();
                // restore autocommit to true for that cxn object. because if the same object is obtained from the CxnPool later, autocommit will be false
                cxn.setAutoCommit(true);
                return 0;
    
            }
        });
    

    Hope this helps

提交回复
热议问题