---
title: "Spring事务管理器_注解方式"
author: "softdn"
date: "2010-04-28T10:01:11Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2010-04-28T10:01:11Z"
id: 654733
url: "https://softdn.iteye.com/blog/654733"
---

让hibernate 的实现方法具有事务性，用spring事务管理器进行切面管理。

若不具备事务性，

     1）dataSource池 无法管理 连接池，执行一条DB操作，将会打开一个新连接，直到消耗了20个连接后，挂掉，且无法自动回复db 连接。

     2）没有事务性的系统，运行的安全性，可想而知了。

下面是一种比较被合理采用的，也是比较灵活的，注解方式 声明 给 spring 事务管理器。

配置文件比较简单，无须扩展，只要在操作DB时，方法声明  @Transactional 即可。

 

1: applicationContext.xml ----------------------------------------------------------------------------

&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;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"&gt;  
             
    &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close"&gt;  
        &lt;property name="driverClassName" value="com.mysql.jdbc.Driver"&gt;&lt;/property&gt;  
        &lt;property name="url" value="jdbc:mysql://localhost:3306/wysosdb?useUnicode=true&amp;characterEncoding=utf-8"&gt;&lt;/property&gt;  
        &lt;property name="username" value="root"&gt;&lt;/property&gt;  
        &lt;property name="password" value="softdn"&gt;&lt;/property&gt;  
        &lt;property name="maxActive" value="100"&gt;&lt;/property&gt;  
        &lt;property name="maxIdle" value="10"&gt;&lt;/property&gt;  
        &lt;property name="maxWait" value="500"&gt;&lt;/property&gt;  
        &lt;property name="defaultAutoCommit" value="false"&gt;&lt;/property&gt;  
    &lt;/bean&gt;  
    &lt;!-- hibernate 的会话工厂 --&gt;  
    &lt;bean id="sessionFactory"  
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt;  
        &lt;property name="configLocation" value="classpath:hibernate.cfg.xml" /&gt;  
        &lt;property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" /&gt;  
        &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt;  
        &lt;property name="hibernateProperties"&gt;  
            &lt;props&gt;  
                &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt;  
                &lt;prop key="hibernate.show\_sql"&gt;true&lt;/prop&gt;&lt;!-- 显示SQL，为了方便测试 --&gt;  
            &lt;/props&gt;  
        &lt;/property&gt;  
        &lt;property name="mappingResources"&gt;  
            &lt;list&gt;&lt;!-- 映射文件 --&gt;  
                &lt;value&gt;db/table/Member.hbm.xml&lt;/value&gt;  
            &lt;/list&gt;  
        &lt;/property&gt;  
    &lt;/bean&gt;  
         
    &lt;!-- 定义事务管理器（声明式的事务）(针对hibernate的事务管理器) --&gt;  
    &lt;bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt;  
        &lt;!-- 配置HibernateTransactionManager时需要依注入 SessionFactory的引用 --&gt;  
        &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt;  
    &lt;/bean&gt;  
    &lt;!-- 采用@Transaction注解的方式使用事务 --&gt;  
    &lt;tx:annotation-driven transaction-manager="txManager"/&gt;         
     
    &lt;!-- 把Session工厂注入给hibernateTemplate --&gt;  
    &lt;!-- 解释一下hibernateTemplate：hibernateTemplate提供了很多方便的方法，在执行时自动建立 HibernateCallback 对象，例如：load()、get()、save、delete()等方法。 --&gt;  
    &lt;bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"&gt;  
       &lt;constructor-arg&gt;  
           &lt;ref local="sessionFactory"/&gt;  
       &lt;/constructor-arg&gt;  
    &lt;/bean&gt;  
    &lt;!-- 以下注入是Member Table 开始于 55555 结束于55555 --&gt;  
    &lt;bean id="memberDao" class="db.dao.impl.MemberDaoImpl" scope="singleton"&gt;  
        &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt;  
    &lt;/bean&gt;  
    &lt;bean id="memberService" class="service.impl.MemberServiceImpl" scope="prototype"&gt;  
        &lt;property name="memberDao" ref="memberDao"&gt;&lt;/property&gt;  
    &lt;/bean&gt;

 

&lt;/beans&gt;

 

 

2:daoImpl 方法调用

    /\**  
     * 根据 VO 查询 List  
     \*/  
    @Transactional  
    public List&lt;Task&gt; listTaskByExample(Task task, Order order)  
            throws Exception {  
        List&lt;Task&gt; list = null;  
        // -----1,Check session is open or not, and open it  
         
        // -----2,Create criteria for the bean class  
        Criteria cs  = this.getSession().createCriteria(Task.class);  
        cs.add(Example.create(task));  
        if (null != task.getTaskId()){  
            cs.add(Expression.eq("taskId", task.getTaskId()));  
        }  
         
        // -----3,Build the Order  
        if (order != null){  
            cs.addOrder(order);  
        }  
         
        // -----4,Exe  
        list =  cs.list();  
         
        // -----5,finally Close session  
         
        // -----6,Return  
        return list;         
    }