如何在Spring JDBC模板中将自动提交设置为false [英] How to set autocommit to false in spring jdbc template

查看:135
本文介绍了如何在Spring JDBC模板中将自动提交设置为false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在春季通过将属性添加到数据源bean id来将autocommit设置为false,如下所示:

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

   <property name="defaultAutoCommit" value="false" /> 

但是在执行我的过程之前,我需要在单个java方法中专门添加它. 我使用了以下代码段.

But i need to add it specifically in a single java method before executing my procedure. I used the below code snippet.

  getJdbcTemplate().getDataSource().getConnection().setAutoCommit(false);

但是以上行没有将autocommit设置为false?
我有什么想念的吗?
或通过spring在特定的java方法中设置自动提交的任何替代方法

But the above line was not setting autocommit to false?
Am i missing anything ?
or any alternative to set autocommit in a specific java method by spring

谢谢

推荐答案

问题是您在Connection上设置了自动提交,但JdbcTemplate却不记得Connection了.取而代之的是,它为每个操作获取一个新的Connection,并且该Connection实例可能相同也可能不同,具体取决于您的DataSource实现.由于defaultAutoCommit不是DataSource的属性,因此有两个选择:

The problem is that you are setting autocommit on a Connection, but JdbcTemplate doesn't remember that Connection; instead, it gets a new Connection for each operation, and that might or might not be the same Connection instance, depending on your DataSource implementation. Since defaultAutoCommit is not a property on DataSource, you have two options:

  1. 假设您的具体数据源具有用于defaultAutoCommit的设置器(例如,
  1. Assuming your concrete datasource has a setter for defaultAutoCommit (for example, org.apache.commons.dbcp.BasicDataSource), cast the DataSource to your concrete implementation. Of course this means that you can no longer change your DataSource in your Spring configuration, which defeats the purpose of dependency injection.

((BasicDataSource)getJdbcTemplate().getDataSource()).setDefaultAutoCommit(false);

  1. DataSource设置为包装器实现,该实现将在每次获取连接时将AutoCommit设置为false.

  1. Set the DataSource to a wrapper implementation that sets AutoCommit to false each time you fetch a connection.

final DataSource ds = getJdbcTemplate().getDataSource();
getJdbcTemplate().setDataSource(new DataSource(){
  // You'll need to implement all the methods, simply delegating to ds

  @Override
  public Connection getConnection() throws SQLException {
    Connection c = ds.getConnection();
    c.setAutoCommit(false);
    return c;
  }
});

这篇关于如何在Spring JDBC模板中将自动提交设置为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆