使用Spring JdbcTemplate协调跨多个Daos的事务

时间:2014-05-07 15:51:39

标签: java spring transactions

我有一个包含服务层的体系结构,其中每个服务类可以注入一个或多个dao类。

我理解如何在扩展JdbcDaoSupport的daos中创建和执行事务。但是,我希望对服务层中的事务进行更高级别的控制,并使事务跨越多个daos进行多次调用。

public class JdbcUserAccountDao extends JdbcDaoSupport implements UserAccountDao {
    private TransactionTemplate transactionTemplate;

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    @Override
    public void changeUserDetails(final String someString) throws Exception {        

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status)  {
            try { 
                getJdbcTemplate().update(some table);
                getJdbcTemplate().update(some other table);
            }   
            catch (Exception ex) {
                status.setRollbackOnly();                    
                throw new RuntimeException(ex);
            }
        }
    });
}

Spring上下文代码段:

<bean id="userAccountDao" class="com.xxx.api.dao.jdbc.JdbcUserAccountDao">
    <property name="dataSource" ref="dataSource"/>
    <property name="transactionTemplate" ref="txTemplate"/>
</bean>

<bean id="txTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager"/>
</bean>

层次结构的一个级别,即服务类:

public class UserServiceImpl implements UserService {
    private UserAccountDao userAccountDao;
    private SomeOtherDao someOtherDao;

    public void setUserAccountDao(UserAccountDao userAccountDao) {
        this.userAccountDao = userAccountDao;
    }

    public void setSomeOtherDao (SomeOtherDao someOtherDao ) {
        this.someOtherDao = someOtherDao ;
    }

    public void changeUserAndSomeOtherStuff(String details) {

        // Would like transaction to start here ...

        userAccountDao.changeUserDetails(details);
        someOtherDao.changeSomethingElse(details);

        // ... and end here.
    }
}

服务层bean自然会注入两个Daos。

<bean id="userService" class="com.xxx.api.service.impl.UserServiceImpl">
    <property name="userAccountDao" ref="userAccountDao"/>
    <property name="someOtherDao" ref="someOtherDao"/>
</bean>

我想在我的服务层中启动和结束事务并跨越对不同Daos的调用。这可能吗?谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,我会将事务隔离传播设置为Propagation.REQUIRED。

例如,在我写的服务中(但请注意我使用了注释):

@Transactional(propagation=Propagation.REQUIRED)
public void save(T t) throws Exception {
    try {

        dao.save(t);
    } catch (Exception e) {

        logger.fatal("Errore nel salvataggio dell'entità di tipo "
                + t.getClass().getName(), e);
        throw e;
    }
}

我希望这会有所帮助

安吉洛