Spring 事务模板

最近项目开发中需要用到单机事务,因为项目中使用了Spring和Mybatis框架,所以通过Spring来进行事务的管理,并且记录一下事务配置的过程

第一步:配置DataSource

<!-- 发票服务化主数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
	<property name="driverClassName" value="${jdbc_driver}" />
	<property name="url" value="${jdbc_url}" />
	<property name="username" value="${jdbc_user}" />
	<property name="password" value="${jdbc_password}" />  
</bean>

 

第二步:配置SqlSessionFactory

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations">
            <list>
                <value>mapper.xml位置</value>
            </list>
        </property>
        <property name="typeAliasesPackage" value="xxx.xxx.xxx"/>
    </bean>

 

第三步:对数据源进行事务管理

<bean id="transactionManager" 
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        p:dataSource-ref="dataSource" factory-bean="sqlSessionFactory"/>

  

第四步:配置事务模板

<!--事务模板 -->
    <bean id="transactionTemplate"
          class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager">
            <ref local="transactionManager" />
        </property>
    </bean>

第五步:在代码中使用

@Service
public class OrderServicempl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Override
    public boolean createOrder(OrderVO order) {

        //事务--插入开票请求--更新票据状态
        transactionTemplate.execute((TransactionCallback) transactionStatus -> {
	     orderMapper.insert(order);
             orderItemMapper.insert(order.getItem());
	     return null;
        });

        return ResultUtils.createResult(Boolean.TRUE);
    }
}

  

posted @ 2017-07-18 18:02  googlemeoften  阅读(1025)  评论(0编辑  收藏  举报