springmvc配置事务

本文介绍了如何在SpringMVC中配置事务管理,包括在`application.xml`中设置`DataSourceTransactionManager`,定义事务属性,以及在Service实现类中添加异常处理机制。通过事务顾问和切入点表达式确保特定方法在事务范围内执行,并处理可能的异常情况。
摘要由CSDN通过智能技术生成

1.springmvc配置事务,先在application.xm中配置事务

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <tx:advice id="txAdvice" transaction-manager="transactionManager">  
        <tx:attributes>  
            <!-- <tx:method name="get*" read-only="true" rollback-for="java.lang.Exception"  />     -->
            <tx:method name="query*" read-only="true" />  
            <tx:method name="select*" read-only="true" />
            <tx:method name="insert*"  propagation="REQUIRED"  rollback-for="java.lang.Exception"/>
            <!-- <tx:method name="*" rollback-for="java.lang.Exception"/> --><!-- 默认回滚机制是RuntimeException   -->
        </tx:attributes>  
    </tx:advice>      
     
    <aop:config>  
        <aop:pointcut id="service" expression="execution(* com.oracle.sx.businessData.service..*ServiceImpl.*(..))" /><!-- 声明所有包含Service的类的所有方法使用事务   -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="service" />  
    </aop:config>  
   
2.在对应的*ServiceImpl(Service实现类)对应的方法添加异常机制,如下:

@Override
    
public String addDept(JSONObject obj) throws Exception {
        DepartmentInfo departmentInfo = new DepartmentInfo();
        String retCode ="";
        String retMsg = "";
        String objStr = "";
//        Map<String, Object> params = new HashMap<String, Object>();
        JSONObject jsonObject = new JSONObject();
        try{
           业务块
        }catch(Exception e){
            retCode = GET_MESSAGE_CODE.UNKNOWN_ERROR;
            retMsg = "未知错误";
            log.info("接口异常信息:" + e);
            throw new Exception();
        }
        jsonObject.put("response",retCode);
        jsonObject.put("message", retMsg);
        //转换JSON
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObject);
        objStr = jsonArray.toJSONString();
        return objStr;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值