如何在Spring JDBC模板中将自动提交设置为false [英] How to set autocommit to false in spring jdbc template
问题描述
目前,我正在春季通过将属性添加到数据源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:
- Assuming your concrete datasource has a setter for
defaultAutoCommit
(for example, org.apache.commons.dbcp.BasicDataSource), cast theDataSource
to your concrete implementation. Of course this means that you can no longer change yourDataSource
in your Spring configuration, which defeats the purpose of dependency injection.
((BasicDataSource)getJdbcTemplate().getDataSource()).setDefaultAutoCommit(false);
-
将
DataSource
设置为包装器实现,该实现将在每次获取连接时将AutoCommit设置为false.
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屋!