了Spring JDBC模板的setAutoCommit(假)

问题描述 投票:0回答:1

我想在插入数据库表的多个行。我使用了Spring JDBC。我怎么可以在Spring的JDBC连接管理的事务。我的代码是:

@Override
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public int addUserRelationshipMapping(final ArrayList<UserDO> userDOs, final long userId) throws UserDataException {
    final JdbcTemplate jd = this.getJdbctemplate();
    try {
        jd.getDataSource().getConnection().setAutoCommit(false);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    int totalAdded = 0;
    try {
        int[] isAdded = jd.batchUpdate(ADD_USER_RELATION_MAPPING, new BatchPreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                final long userRelationId = jd.queryForObject(USER_RELATION_KEY, Long.class);
                UserDO userDO = userDOs.get(i);
                    ps.setLong(1, userRelationId);
                    ps.setLong(2, userId);
                    ps.setLong(3, userDO.getprimaryUserId());
                    ps.setInt(4, 1);
                    ps.setInt(5, 0);
                    jd.getDataSource().getConnection().commit();
            }

            @Override
            public int getBatchSize() {
                return userDOs.size();
            }
        });
        totalAdded = isAdded.length;
    } catch (DuplicateKeyException dExp) {
        log.info("error for duplicate key exception ",dExp);
        log.error(dExp);

    } catch (DataAccessException dExp) {
        throw new UserDataException("error while adding user relation for userId is" + userId, dExp);
    }
    return totalAdded;
}

在此代码userRelationId总是返回不更新表值旧值。所以将使用数据库连接提交。

SOF问题:Java MYSQL/JDBC query is returning stale data from cached Connection

我得到错误信息:

值java.sql.SQLException:由造成无法调用commit时自动提交=真

所以,我需要帮助这一点。先谢谢了。

java spring jdbc spring-jdbc
1个回答
0
投票

查看如何设置自动提交虚假的例子

<bean id="database" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
    <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        ...
        <property name="defaultAutoCommit" value="false" />
        ...
    </bean>
</property>

REF:spring 3.1: jdbcTemplate auto commit to false.

您也可以尝试使用基于注解关联交易管理? How can I config to turn off autocommit in Spring + JDBC?

© www.soinside.com 2019 - 2024. All rights reserved.