spring事务管理

来源:互联网 发布:淘宝联盟旧版本4.3.2 编辑:程序博客网 时间:2024/06/03 20:16

--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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"     
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
   <!--使用注解,自动扫描com.newlandcomputer.nlsystem下面的包-->      
 <context:component-scan base-package="com.newlandcomputer.nlsystem"/>

 

<!--使用jdbc.properties属性文件,数据库连接配置在这个属性文件中已经配置好了-->

 <bean id="mappings"   
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations" value="classpath:jdbc.properties"></property>   
      </bean>   
     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
         destroy-method="close">  
         <property name="driverClassName" value="${jdbc.driver}" />  
         <property name="url" value="${jdbc.url}" />  
         <property name="username" value="${jdbc.username}" />  
         <property name="password" value="${jdbc.password}" />
         
         <property name="initialSize" value="5" />
         <property name="maxActive" value="100" />
         <property name="maxIdle" value="30" />
         <property name="maxWait" value="500" />
         <property name="poolPreparedStatements" value="false" />
         <property name="defaultAutoCommit" value="false" />  
     </bean>  
       
        <!-- 读取数据库配置文件 -->
     <context:property-placeholder location="classpath:jdbc.properties" />
     
     <!-- Hibernate配置 -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
                <property name="dataSource" ref="dataSource" />
                <property name="namingStrategy">
                    <bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
                </property>
                <property name="hibernateProperties">
                    <props>
                        <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                        <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                        <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                    </props>
                </property>

                <property name="packagesToScan">
                    <list>
                        
                    </list>
                </property>
        
                <property name="annotatedClasses">
                    <list>
                        <!--这里的类是代表实体类-->
                        <value>com.newlandcomputer.nlsystem.pojo.Student</value>
                        <value>com.newlandcomputer.nlsystem.pojo.BorrowRecord</value>
                    </list>
                </property>
            
        </bean>
        
        <bean id="transactionManager"
            class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory" />
        </bean>
    <!--第一种方法: 事务注解配置 。注解配置事务,只需要在类名前加这个注解“@Transactional”-->
    <!-- <tx:annotation-driven transaction-manager="transactionManager"/> -->

   <!--第二种方法: 使用拦截器 -->
 <!--
      <bean id="transactionInterceptor"    
         class="org.springframework.transaction.interceptor.TransactionInterceptor">    
         <property name="transactionManager" ref="transactionManager" />    
         <property name="transactionAttributes">    

             <props>

                   <!--

                     * PROPAGATION_REQUIRED--支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
                    * PROPAGATION_SUPPORTS--支持当前事务,如果当前没有事务,就以非事务方式执行。
                    * PROPAGATION_MANDATORY--支持当前事务,如果当前没有事务,就抛出异常。
                    * PROPAGATION_REQUIRES_NEW--新建事务,如果当前存在事务,把当前事务挂起。

                    * PROPAGATION_NOT_SUPPORTED--以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。

                    * PROPAGATION_NEVER--以非事务方式执行,如果当前存在事务,则抛出异常。 

                   --> 

                  <!--默认只有runtimeException才会促使事务回滚,加上-Exception代表Exception类异常以及它的所有子类都进行事务回滚-->

                 <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
             </props>    
         </property>    
     </bean>  
         
     <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">    
         <property name="beanNames">    

             <list>   

                    <!--代表需要进行事务管理的类,*是通配符,这里说明是代表所有还要Service的类-->

                 <value>*Service</value>
             </list>    
         </property>    
         <property name="interceptorNames">    
             <list>    
                 <value>transactionInterceptor</value>
             </list>    
         </property>    
     </bean>         
-->   
 
     <!-- 第三种方法:使用tx标签配置的拦截器 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">  
           <tx:attributes>
           <!-- tx:method相关属性
                   (属性)        (是否必须)(默认值)      (描述)
                name                  是                                              与事务属性关联的方法名。通配符(*)可以用来指定一批关联到相同的事务属性的方法。如:'get*'、'handle*'等
                propagation         不                  REQUIRED     事务传播行为
                isolation               不                  DEFAULT         事务隔离级别
                timeout                 不                   -1                     事务超时的时间(以秒为单位)
                read-only              不                  false                事务是否只读?
                rollback-for          不                                            将被触发进行回滚的 Exception(s);以逗号分开。如:'com.foo.MyBusinessException,ServletException'
                no-rollback-for    不                                             不 被触发进行回滚的 Exception(s);以逗号分开。如:'com.foo.MyBusinessException
            -->
               <tx:method name="*" propagation="REQUIRED"/>  
           </tx:attributes>  
       </tx:advice>  
         
       <aop:config>
       <!--
               |第一个 * —— 通配 任意返回值类型
            |第二个 * —— 通配 包com.evan.crm.service下的任意class
            |第三个 * —— 通配 包com.evan.crm.service下的任意class的任意方法
            |第四个 .. —— 通配 方法可以有0个或多个参数
         -->
           <aop:pointcut id="interceptorPointCuts"  
               expression="execution(* com.newlandcomputer.nlsystem.service..*.*(..))" />  
           <aop:advisor advice-ref="txAdvice"  
               pointcut-ref="interceptorPointCuts" />          
       </aop:config>  

</beans>


---我这里是在Service层进行事务管理的,也建议在Service层进行事务管理。以下是Service层的类

package com.newlandcomputer.nlsystem.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.newlandcomputer.nlsystem.dao.BorrowRecordDao;
import com.newlandcomputer.nlsystem.dao.StudentDao;
import com.newlandcomputer.nlsystem.pojo.BorrowRecord;
import com.newlandcomputer.nlsystem.pojo.Student;
import com.newlandcomputer.nlsystem.util.NewlandException;
import com.sun.org.omg.CORBA.ExceptionDescription;

/**
 *
* 项目名称:newland  
* 类名称:MenuService  
* 类描述:  
* 创建人:hc  
* 创建时间:2011-9-4 下午06:35:18
 */
@Service
//@Transactional(如果使用注解配置事务,这里的注释要去掉)
public class StudentService  {

    private static Logger log = Logger.getLogger(StudentService.class);
    @Autowired
    private StudentDao studentDao;
    @Autowired BorrowRecordDao borrowRecordDao;

    //@Transactional(注解配置事务的时候,这个注解表示这个方法进行事务管理)
    public void delStudent(Student student) throws Exception{
            //删除学生信息
            studentDao.delStudent(student);
            //查找这个学生的所有借书记录
            List<BorrowRecord> list = borrowRecordDao.findBorrowRecordByStudentId(student.getStudentId());
            //删除这个学生对应的借书记录
            if(null != list && list.size() > 0){
                for (int i = 0; i < list.size(); i++) {
                    borrowRecordDao.delBorrowRecord(list.get(i));
                    System.out.println("学生ID:"+list.get(i).getStudentId());
                }
            }
//            throw new RuntimeException("运行时异常!");
            throw new Exception("所有异常都抛出!");
    }
}


--以下是Dao层里的方法

package com.newlandcomputer.nlsystem.dao;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.newlandcomputer.nlsystem.pojo.BorrowRecord;
import com.newlandcomputer.nlsystem.util.NewlandException;

/**
 *
* 项目名称:newland  </br>
* 类名称:BorrowRecordDao  </br>
* 类描述:  学生借书记录的Dao类</br>
* 创建人:hc  </br>
* 创建时间:2011-10-24 上午09:12:13
 */
@Repository
public class BorrowRecordDao extends HibernateDaoSupport{

    @Resource
    private SessionFactory sessionFactory;
    @Autowired
    public void setSessionFactory0(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }
    private static Logger log = Logger.getLogger(BorrowRecordDao.class);
    

    
    /**
     * 删除借书记录
     * @param borrowRecord
     * @throws NewlandException
     */
    public void delBorrowRecord(BorrowRecord borrowRecord) throws NewlandException{
        log.info("删除借书记录!");
        try{
            this.getHibernateTemplate().delete(borrowRecord);
        }catch (Exception e) {
            throw new NewlandException("删除借书记录出错:"+e.getMessage());
        }
    }
    
    /**
     * 根据studentid查询借书记录信息
     * @return List
     * @throws NewlandException
     */
    public List<BorrowRecord> findBorrowRecordByStudentId(String studentid) throws NewlandException{
        log.info("分页查询借书记录!");
        String hql = "from BorrowRecord b where b.studentId=:studentid";
        Session session = null;
        try{
            session = sessionFactory.openSession();
            Query query = session.createQuery(hql);
            query.setString("studentid", studentid);
            return query.list();
        }catch (Exception e) {e.printStackTrace();
            log.error("根据studentid查询借书记录出错:"+e.getMessage());
            throw new NewlandException("根据studentid查询借书记录出错:"+e.getMessage());
        }
    }
}


package com.newlandcomputer.nlsystem.dao;



import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.newlandcomputer.nlsystem.pojo.Student;
import com.newlandcomputer.nlsystem.util.NewlandException;

/**
 *
* 项目名称:newland  </br>
* 类名称:StudentDao  </br>
* 类描述:  学生信息的Dao类</br>
* 创建人:hc  </br>
* 创建时间:2011-10-21 下午05:09:14
 */
@Repository
public class StudentDao extends HibernateDaoSupport{

    @Autowired
    public void setSessionFactory0(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }


    private static Logger log = Logger.getLogger(StudentDao.class);
    
    /**
     * 删除学生
     * @param student
     * @throws NewlandException
     */
    public void delStudent(Student student) throws NewlandException{
        log.info("删除学生!");
        try{
            this.getHibernateTemplate().delete(student);
        }catch (Exception e) {
            throw new NewlandException("删除学生出错:"+e.getMessage());
        }
    }
    
}




原创粉丝点击