spring mybatis事务回滚配置

1、配置mybatis数据源

    
    <bean id="writeTransactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="writeDataSource" />
    bean>

    
    <tx:annotation-driven transaction-manager="writeTransactionManager" proxy-target-class = "true"/>

    <bean id="writeDataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${master.driver}" />
        <property name="url" value="${master.url}" />
        <property name="username" value="${master.username}" />
        <property name="password" value="${master.password}" />
        
        <property name="maxActive" value="${master.maxActive}">property>
        <property name="maxIdle" value="${master.maxIdle}">property>
        <property name="minIdle" value="${master.minIdle}">property>
        <property name="maxWait" value="${master.maxWait}">property>
        
        <property name="timeBetweenEvictionRunsMillis" value="${master.timeBetweenEvictionRunsMillis}" />
        
        <property name="minEvictableIdleTimeMillis" value="${master.minEvictableIdleTimeMillis}"/>
    bean>

    <bean id="writeSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="writeDataSource" />
        
        <property name="mapperLocations" value="classpath*:write/**/*.xml">property>
        
        <property name="configLocation" value="classpath:mybatis/mybatis-configuration.xml">property>
    bean>

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

2、代码里在方法上设置@Transactional注解

3、只有继承自RuntimeException的异常才会被事务捕获然后回滚(这个是重点)

    @Transactional
    public void insertLog() throws Exception{
        logDao.insertTest();
        Log log = new Log();
        log.setDesc("1111111");
        logDao.insert(log);
        if(true){
            throw new RuntimeException("1111");
        }
    }

还有个坑就是如果用MySQL数据库,数据库表你如果是自动建表,那么就需要把建表的Engine设置为InnoDB格式,自动建表的格式为:MyISAM,这中格式的是不支持事务管理的。这个我实验过,MyISAM确实不支持事务。

mybatis里#与的区别就是#会把传递的参数当字符串解析,而 就简单的直接把参数合成sql语句,一定程度上#可以防止sql注入。

你可能感兴趣的:(web开发)