spring对事务的捕获

来源:互联网 发布:陈一发唱歌软件 编辑:程序博客网 时间:2024/05/17 05:50

写于前面

原来是记得的,为什么现在又忘记勒~

异常种类

1、运行时异常,RuntimeException
2、检查式异常,需要try catch
这两个很容易区分的,比如你写代码时候 强制让你thows 或者try catch 就是检查式异常

/**     * @Description: 运行时异常,常见种类有以下几种     * @see: NullPointerException,     * @see: IndexOutOfBoundsException     * @see:NumberFormatException     * @see:ClassCastException 类型转换错误     * @see:ArrayStoreException 类型转换错误     * @return:void     */    private void unCheckedException() {        // List list = null;list.get(0);//NullPointerException        // new ArrayList().get(1);//IndexOutOfBoundsException        // Integer.parseInt("dd");//NumberFormatException        // List aa=(List)new ExceptionType();//ClassCastException        /**         * Object[] in = { 1, 2 }; in = new Integer[5]; in[1] = "123";//ArrayStoreException         **/    }

spring事务

随着spring的迭代,spring事务的写法有很多种,但是原理都是类似,知道原理自己就不怕了。
spring只支持运行时异常回滚,可以自己测试~
这里介绍两种方式的
声明式事务:

<!-- 事务管理器 -->    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" />    <!-- 配置事务边界 -->    <aop:config>        <aop:pointcut id="serviceMethod" expression="execution(* com.team.youdao.service.*.*(..))" />        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />    </aop:config>    <!--配置事务的传播特性 -->    <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>        <!-- 如果service的方法名不是以下开头的,就无法修改数据,例如插入,更新 只能查询readonly -->            <tx:method name="save*" propagation="REQUIRED" />            <tx:method name="del*" propagation="REQUIRED" />            <tx:method name="update*" propagation="REQUIRED" />            <tx:method name="do*" propagation="REQUIRED" />            <tx:method name="*" propagation="REQUIRED" read-only="true" />        </tx:attributes>    </tx:advice>

注解式事务:

<!-- 定义事务 -->    <bean id="transactionManagers" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSources" />    </bean>    <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务 -->    <tx:annotation-driven transaction-manager="transactionManagers" proxy-target-class="true" />

代码里面使用都是在类上面加上,只是声明式事务会对方法命名有要求,千万不要弄错方法命名,不然会导致数据无法插入或者更新等等,如果使用注解式事务区别就在于一个readOnly = true或者false

@Service@Transactional(readOnly = true)

或者去掉@Service 声明式在xml里面添加这个类的bean
需要插入或者修改数据库的方法头上加这些

@Transactional(readOnly = true)
1 让checked例外也回滚:在整个方法前加上 @Transactional(rollbackFor=Exception.class) 2 让unchecked例外不回滚: @Transactional(notRollbackFor=RunTimeException.class) 3 不需要事务管理的(只查询的)方法:@Transactional(propagation=Propagation.NOT_SUPPORTED) 在整个方法运行前就不会开启事务        还可以加上:@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true),这样就做成一个只读事务,可以提高效率。 
0 0
原创粉丝点击