spring和mybatis事务配置不起作用,跪求高手指点

javaSir 发布于 2014/07/18 15:13
阅读 4K+
收藏 0

 下面是配置文件applicationContext.xml;


<?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:aop="http://www.springframework.org/schema/aop
  xmlns:tx="http://www.springframework.org/schema/tx"  
  xmlns:jdbc="http://www.springframework.org/schema/jdbc
  xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="         
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd         
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd         
      http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd         
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
     >
     
    <!-- jdbc属性文件读入 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>
     
 <!-- 数据库连接池 -->
 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
  <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="minPoolSize" value="5"/>
   
    <!--连接池中保留的最大连接数。Default: 15 -->
    <property name="maxPoolSize" value="30"/>
   
    <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
    <property name="initialPoolSize" value="10"/>
   
    <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
    <property name="maxIdleTime" value="10"/>
   
    <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
    <property name="acquireIncrement" value="5"/>
   
    <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。
      但由于预缓存的statements属于单个connection而不是整个连接池。所以设
      置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection
      均为0,则缓存被关闭。Default: 0-->
    <property name="maxStatements" value="0"/>
   
    <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
    <property name="idleConnectionTestPeriod" value="60"/>
   
    <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
    <property name="acquireRetryAttempts" value="30"/>
   
    <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据
      源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设
      为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。Default: false-->
    <property name="breakAfterAcquireFailure" value="true"/>
   
    <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection
      提交的时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable
      等方法来提升连接测试的性能。Default: false -->
    <property name="testConnectionOnCheckout" value="false"/>
 </bean>
 
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource"></property>
  <property name="configLocation" value="classpath:mybatis-config.xml"/>  
 </bean>
 
 <bean id="sqlSession"
  class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg index="0" ref="sqlSessionFactory" />
 </bean>
 
 <bean name="transactionManager"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"></property>
 </bean>
 
 <!-- 启用事务 -->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
    <tx:method name="save*"   propagation="REQUIRED"  rollback-for="com.inspur.*.exception.CRUDException,Exception" />
       <tx:method name="create*" propagation="REQUIRED"  rollback-for="com.inspur.*.exception.CRUDException,Exception" />
       <tx:method name="copy*"   propagation="REQUIRED"  rollback-for="com.inspur.*.exception.CRUDException,Exception" />
       <tx:method name="update*" propagation="REQUIRED"  rollback-for="com.inspur.*.exception.CRUDException,Exception" />
       <tx:method name="delete*" propagation="REQUIRED"  rollback-for="com.inspur.*.exception.CRUDException,Exception" />
       <tx:method name="find*"   read-only="true" rollback-for="com.inspur.*.exception.CRUDException,Exception" />
       <tx:method name="list*"   read-only="true" rollback-for="com.inspur.*.exception.CRUDException,Exception" />
       <tx:method name="is*" read-only="true" rollback-for="com.inspur.*.exception.CRUDException,Exception" />
       <tx:method name="*"  read-only="true" rollback-for="com.inspur.*.exception.CRUDException,Exception" />
  </tx:attributes>
 </tx:advice>
 
 <!-- AOP代理设置 -->
 <aop:config>
        <aop:advisor pointcut="execution(* com.inspur.*.service.*.*(..))" advice-ref="txAdvice" />
 </aop:config>

 <!-- scan  mappers and let them be autowired -->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">      
  <property name="basePackage" value="com.inspur.courseSalarySys.persistence,com.inspur.framework.persistence" />
 </bean>
 
  <!-- 激活annotation功能    作用是式地向 Spring 容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、
      PersistenceAnnotationBeanPostProcessor 以及 RequiredAnnotationBeanPostProcessor 这 4 个BeanPostProcessor。
             注册这4个 BeanPostProcessor的作用,就是为了你的系统能够识别相应的注解。识别各种注解-->
 <context:annotation-config />
 <context:spring-configured/>
 
</beans>

在service中故意设置异常如下,不进行回滚,跪求指点!

 /**
  * 保存
  * @param course
  * @throws CRUDException
  */
 public void saveCourse(Course course) throws CRUDException {
     try{
   course.setId(Util.getUUID());
      courseMapper.saveCourse(course);
      Course cr  = new Course();
      System.out.println(Integer.parseInt("dsdfsf"));
      System.out.println(cr.getId().equals(""));
     }catch(Exception e){
    log.error(e);
    throw new CRUDException(e);
     }
 }
 

加载中
0
len
len
    <!-- Transaction start -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- Transaction end -->


使用时:



    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = {RuntimeException.class, Exception.class})

javaSir
javaSir
你好?aop配置不可以吗
0
len
len
我是没配置,在用的时候申明的。你这种没有用过,但看起来应该不像有问题。你可以多在网上找找例子对比一下。
javaSir
javaSir
我按照上面的方式设置,发现事务还是不起作用,着急,能帮我看下嘛,按照评论下方写的
javaSir
javaSir
谢谢
0
javaSir
javaSir

 配置文件中这么写的的
 <tx:annotation-driven transaction-manager="transactionManager"/>


@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
 public void saveCourse(Course course) throws Exception {
     try{
   course.setId(Util.getUUID());
      courseMapper.saveCourse(course);
      Course cr  = new Course();
      System.out.println(cr.getId().equals(""));
     }catch(Exception e){
    log.error(e);
    throw new CRUDException(e);
     }
 }
我故意有设置空指针异常,事务还是不起作用,找不到问题出在哪里,急

0
len
len
数据库是什么?
0
len
len
你等等,我试一下。
0
len
len
<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.2.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
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


    <context:property-placeholder location="classpath:oracle.properties"></context:property-placeholder>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:com/fishbone/**/mapper/oracle/*.xml"/>
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

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

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

    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- Transaction end -->

    <aop:config>
        <aop:pointcut id="serviceOperation" expression="execution(* com.fishbone..*.dao..*Service.*(..))"/>
        <aop:advisor pointcut-ref="serviceOperation" advice-ref="txAdvice"/>
    </aop:config>

    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name=""/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED" rollback-for="Throwable"/>
        </tx:attributes>
    </tx:advice>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@58.68.238.84:1521:sensky"/>
        <property name="username" value="fbus"/>
        <property name="password" value="fbus"/>

        <property name="maxActive" value="20"/>
        <property name="initialSize" value="1"/>
        <property name="maxWait" value="60000"/>
        <property name="minIdle" value="1"/>

        <property name="timeBetweenEvictionRunsMillis" value="3000"/>
        <property name="minEvictableIdleTimeMillis" value="300000"/>

        <property name="validationQuery" value="SELECT 'x' FROM DUAL"/>
        <property name="testWhileIdle" value="true"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>
        <property name="poolPreparedStatements" value="true"/>
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
        <property name="filters" value="mergeStat"/>
        <property name="connectionProperties" value="druid.stat.slowSqlMillis=5000" />
        <property name="timeBetweenLogStatsMillis" value="300000" />
    </bean>
</beans>



0
len
len
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = {RuntimeException.class, Exception.class})
    @RequestMapping(value = "/address", method = RequestMethod.POST)
    public Object add(HttpServletRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView(model + "/add_result");
        RequestUtils req = new RequestUtils(request);
        Address address = (Address) req.create(Address.class);
        address.setCreateDate(new Date());
        address.setLastUpDate(new Date());
        if (Math.abs(address.getLatitude()) > 90 || Math.abs(address.getLongitude()) > 180) {
            throw new MyException(ExpScheme.PARAM_ERR, "亲,你这是在火星上呢");
        }
        User user = (User) request.getAttribute("user");
        ResUserRel ru = new ResUserRel(address.getUuid(), user.getUuid(), ResUserRelType.CREATOR);
        address.getResUserRels().add(ru);
        address = (Address) resParser.parser(request, address);
        int i = addressService.save(address);
        if(true){
          throw new RuntimeException("test");
        }
        if (i == 1) {
            modelAndView.addObject("msg", "成功");
            modelAndView.addObject(model, address);
            modelAndView.addObject("result", ResultScheme.ACT_RESULT_SUCCESS);
            return get(request, address.getUuid());
        } else {
            throw new MyException("未知错误");
        }
    }



0
爪哇小贩
爪哇小贩

看看是不是和我遇到同样问题

http://www.oschina.net/question/818848_117168

返回顶部
顶部