Spring之事务配置

  • 基于注解@Transactional的事物配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.service" />
    <!--加载数据库配置文件-->
    <context:property-placeholder location="classpath:oracle.properties"/>
    <!--配置数据源 c3p0l连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxIdleTime" value="30"/>
        <property name="preferredTestQuery" value="select 1"/>
        <property name="idleConnectionTestPeriod" value="30"/>
        <property name="testConnectionOnCheckout" value="false"/>
    </bean>

    <!--配置SqlSessionFactory-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--加载mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis.cfg.xml"/>
        <property name="dataSource" ref="dataSource"/>
        <!-- 扫描映射文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--基于注解的事务-->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>
  • 具体实例
    finally 里边不能放return!
    finally 里边不能放return!
    finally 里边不能放return!
    这会导致异常被生吃!调用者捕捉不到异常!事务不会起作用!
 public Msg deleteByPrimaryKey(Integer id){
        Msg msg = new Msg();
        try {
            chdMapper.deleteByPrimaryKey(id);
            int re = 100 / 0;
            msg.setCode(100).setContext("删除成功!");
        } catch (Exception e) {
            throw new RuntimeException("删除失败!" + e.getMessage());
        }finally {

        }
        return msg;

    }

猜你喜欢

转载自blog.csdn.net/javacoderwolf/article/details/79910185