【发布时间】:2012-04-06 05:40:18
【问题描述】:
我在基于 Spring JdbcTemplate 的 dao 中有以下代码 -
getJdbcTemplate().update("Record Insert Query...");
int recordId = getJdbcTemplate().queryForInt("SELECT last_insert_id()");
问题是我的 update 和 queryForInt 查询有时会使用来自连接池的不同连接来执行。
这会导致返回不正确的recordId,因为MySql last_insert_id() 应该是从发出插入查询的同一连接中调用的。
我考虑过 SingleConnectionDataSource 但不想使用它,因为它会降低应用程序性能。我只想要这两个查询的单一连接。并非针对所有服务的所有请求。
所以我有两个问题:
- 我可以管理模板类使用的连接吗?
- JdbcTemplate 是否执行自动事务管理?如果我手动将事务应用到我的 Dao 方法,这是否意味着每个查询将创建两个事务?
希望你们能对这个话题有所了解。
更新 - 我尝试了 nwinkler 的方法并将我的服务层包装在一个事务中。一段时间后,我很惊讶地看到同样的错误再次出现。深入研究 Spring 源代码,我发现了这个 -
public <T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action)
throws DataAccessException {
//Lots of code
Connection con = DataSourceUtils.getConnection(getDataSource());
//Lots of code
}
因此与我的想法相反,每个事务不一定有一个数据库连接,但每个执行的查询都有一个连接。 这让我回到了我的问题。我想从同一个连接执行两个查询。 :-(
更新 -
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.jdbc.url}" />
<property name="username" value="${db.user}" />
<property name="password" value="${db.password}" />
<property name="maxActive" value="${db.max.active}" />
<property name="initialSize" value="20" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
autowire="byName">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception" timeout="30" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* service.*.*(..))" />
<aop:pointcut id="pointcut2" expression="execution(* *.ws.*.*(..))" />
<aop:advisor pointcut-ref="pointcut" advice-ref="transactionAdvice" />
<aop:advisor pointcut-ref="pointcut2" advice-ref="transactionAdvice" />
</aop:config>
【问题讨论】:
-
嗯,那我猜你还是做错了什么。您能否发布您的 Spring 配置,包括数据源和事务管理?那个 Spring sn-p 来自哪个班级?你在哪里找到的?
-
该代码来自 JdbcTemplate 类。每当执行查询时都会调用它,因此我对此表示怀疑。
-
请看我更新的答案...
标签: java mysql database spring jdbc