使用@jnsactional和cn.setAutoCommit(false)在spring jdbcTemplate中无法在多个表中插入记录

时间:2017-06-22 16:34:06

标签: java spring oracle spring-jdbc spring-transactions

我在一个DAO类中有一个方法,它在两个不同的Oracle表中插入记录。我希望记录既可以插入表中,也可以不插入。

为了实现这一点,我使用了@Transactionalcn.setAutoCommit(false)代码段。

为了测试它,我故意在SQL中输入错误的列名,以便第二个表中的数据插入失败。我的期望是,由于查询不正确,第二个表中的插入失败,因此数据不会插入第一个表中。但由于某种原因,这并没有发生。记录仍然插入第一个表中,第二个表没有插入记录。

看起来这里的实现并不正确。不知道我在这里缺少什么。

EventLogDao.java

@Transactional
public long saveEventData(EventLog eventLog, String userId) throws SQLException {
        Connection cn = this.dataSource.getConnection();
        cn.setAutoCommit(false);

        //(FIRST TABLE INSERTION - Table Name: EVENT_LOG)
        //save data in event log table 
        long eventId = getNextEventIdSequence();
        saveEventLogData(eventId, eventLog);

        //(SECOND TABLE INSERTION - Table Name: EVENT_LOG_MESSAGE)
        //save data in event log message table
        saveEventLogMessageData(eventId, eventLog.getEventLogMessage());

        cn.commit();
        return eventId;
    }


 private void saveEventLogData(long eventId, EventLog eventLog) {
        Object[] parameters = {eventId, eventLog.getRouteId(), eventLog.getEventType().getEventTypeId(),
            eventLog.getOrderId(), eventLog.getIncomingEventTimestamp(), eventLog.getOutgoingEventTimestamp()};
        int[] types = {Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.VARCHAR, Types.TIMESTAMP, Types.TIMESTAMP};
        int rowsAffected = jdbcTemplate.update(INSERT_EVENT_LOG_SQL2, parameters, types);
        System.out.println("rowsAffected (eventlog) = " + rowsAffected);
    }


private int saveEventLogMessageData(long eventId, EventLogMessage eventLogMessage) {
        Object[] parameters = {eventId, eventLogMessage.getIncomingEventMessage(), eventLogMessage.getOutgoingEventMessage()};
        int[] types = {Types.INTEGER, Types.VARCHAR, Types.VARCHAR};
        int rowsAffected = jdbcTemplate.update(INSERT_EVENT_LOG_MESSAGE_SQL2, parameters, types);
        System.out.println("rowsAffected (eventLogMessage) = " + rowsAffected);
        return rowsAffected;
    }

的applicationContext.xml

<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <constructor-arg>
            <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <property name="dataSource" ref="dataSource"/>
            </bean>
        </constructor-arg>
        <property name="propagationBehavior">
            <util:constant static-field="org.springframework.transaction.support.DefaultTransactionDefinition.PROPAGATION_REQUIRED"/>
        </property>
        <property name="isolationLevel">
            <util:constant static-field="org.springframework.transaction.support.DefaultTransactionDefinition.ISOLATION_READ_COMMITTED"/>
        </property>
    </bean>


<bean id="eventLogDao" class="com.ebayenterprise.publicapi.events.dao.EventLogDao">
    <constructor-arg ref="dataSource" />
</bean>

请指导。

2 个答案:

答案 0 :(得分:0)

我想您应该transactionTemplatejdbcTemplate一起使用

    public long saveEventData(EventLog eventLog, String userId) throws SQLException {
        return transactionTemplate.execute(new TransactionCallback<Long>(){
        @Override
        public Long doInTransaction(TransactionStatus transactionStatus) {
        try {
            Connection cn = this.dataSource.getConnection();
            cn.setAutoCommit(false);

            //(FIRST TABLE INSERTION - Table Name: EVENT_LOG)
            //save data in event log table 
            long eventId = getNextEventIdSequence();
            saveEventLogData(eventId, eventLog);

            //(SECOND TABLE INSERTION - Table Name: EVENT_LOG_MESSAGE)
            //save data in event log message table
            saveEventLogMessageData(eventId, eventLog.getEventLogMessage());

            cn.commit();
            return eventId;
        } catch (Exception e) {
            transactionStatus.setRollbackOnly();
        }
        return 0;
    }

});

您可能没有为JTA配置,而您的@Transactional无效。

答案 1 :(得分:0)

使用TransactionManager让它工作。我对代码库所做的更改如下所述。

applicationContext.xml(已更新)

  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <constructor-arg ref="transactionManager"/>
        <property name="propagationBehavior">
            <util:constant static-field="org.springframework.transaction.support.DefaultTransactionDefinition.PROPAGATION_REQUIRED"/>
        </property>
        <property name="isolationLevel">
            <util:constant static-field="org.springframework.transaction.support.DefaultTransactionDefinition.ISOLATION_READ_COMMITTED"/>
        </property>
    </bean>

<bean id="eventLogDao" class="com.ebayenterprise.publicapi.events.dao.EventLogDao">
    <constructor-arg index="0" ref="dataSource" />
    <constructor-arg index="1" ref="transactionManager"/>
</bean>

EventLogDao.java(已更新)

 public EventLogDao(DataSource dataSource, PlatformTransactionManager transactionManager) {
        super(dataSource, transactionManager);
    }

    public long save(EventLog eventLog, String userId) throws Exception {
        TransactionDefinition txDef = new DefaultTransactionDefinition();
        TransactionStatus txStatus = transactionManager.getTransaction(txDef);
        long eventId = 0L;
        try {
            eventId = getNextEventIdSequence();
            System.out.println("eventId = " + eventId);
            saveEventLogData(eventId, eventLog);
            saveEventLogMessageData(eventId, eventLog.getEventLogMessage());
            userId = StringUtils.defaultIfBlank(userId, DEFAULT_USER_ID);
            saveEventLogAuditData(eventId, userId, eventLog.getOutgoingEventTimestamp());
            transactionManager.commit(txStatus);
        } catch (TransactionException ex) {
            transactionManager.rollback(txStatus);
            throw new RuntimeException("Error occurred during tx management in event log tables...", ex);
        } finally {
            return eventId;
        }
    }