spring管理事物

  1. spring最普通的管理事物

    1.在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.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 内置的连接池:先配置连接池 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    -->


    <!-- 配置DBCP的连接池
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///spring_day03"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
     -->

    <!-- 配置C3P0的连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///mybatis"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!-- 配置JDBC的模板类 -->
    <!-- 配置平台事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 声明式事务(采用XML配置文件的方式) -->
    <!-- 先配置通知 -->
    <tx:advice id="myAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 给方法设置数据库属性(隔离级别,传播行为) -->
            <tx:method name="transfer" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置AOP:如果是自己编写的AOP,使用aop:aspect配置,使用的是Spring框架提供的通知aop:advisor -->
    <aop:config>
        <!-- aop:advisor,是Spring框架提供的通知  (..) 表示有参数  -->
        <aop:advisor advice-ref="myAdvice" pointcut="execution(public * com.tx.server.TxServeriImpl.transfer(..))"/>
    </aop:config>



    <!-- 开启注解的扫描  
    <context:component-scan base-package="com.tx"/>
        -->
    <bean id="txserver" class="com.tx.server.TxServeriImpl">
        <property name="accountdao" ref="accountdao"/>
    </bean>

    <bean id="accountdao" class="com.tx.dao.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

<!--  这个事物是没有注解的,最原始的 -->
<!-- 
    事物其实就是,两条sql执行,如果一条出现了问题,另外一条就进行回滚
    比如转钱:
    小明 扣了一元
    小花就加一元
    可是在小明扣了钱以后出现了错误,
    小明的数据就必须要回滚,不然数据就会错误
 -->
2.dao层的java代码
package com.tx.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import com.tx.bean.PayBean;

/**
 *  extends JdbcDaoSupport  
 *  使用里面的jdbc自带的增删改查的方法
 * @author lenovo
 *
 */
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{


    /**
     *  进钱
     */
    @Override
    public void inMonery(String name, double monery) {
        // TODO Auto-generated method stub

        this.getJdbcTemplate().update("UPDATE pay a set a.money = money + ? WHERE a.name = ?",monery,name);
    }

    /**
     * 扣钱
     * @param otherName 谁
     * @param monery 钱
     */
    @Override
    public void onMonery(String otherName, double monery) {
        // TODO Auto-generated method stub
        this.getJdbcTemplate().update("UPDATE pay a set a.money = money - ? WHERE a.name = ?",monery,otherName);
    }

    @Override
    public void selectAll() {
        // TODO Auto-generated method stub
        List<PayBean> queryForList = this.getJdbcTemplate().query("SELECT * from pay", new TestRowMap());
        for (PayBean payBean : queryForList) {
            System.out.println(payBean.getName());
        }
    }

    /**
     * 回调方法,其实是给查询方法赋值
     * @author lenovo
     *
     */
    class TestRowMap implements RowMapper<PayBean>{

        @Override
        public PayBean mapRow(ResultSet resultSet, int arg1) throws SQLException {
            PayBean payBean = new PayBean();
            payBean.setName(resultSet.getString("name"));
            payBean.setMoney(resultSet.getDouble("money"));
            payBean.setAddname(resultSet.getString("addname"));
            return payBean;
        }

    }
}
3.server层中使用的方法
package com.tx.server;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;

import com.jdbc.bean.UserBean;
import com.tx.bean.PayBean;
import com.tx.dao.AccountDao;

public class TxServeriImpl implements TxServer {

    private Logger log = Logger.getLogger("log");

    //accountdao 必须和xml中配置的id 同名
    public AccountDao accountdao;
    public void setAccountdao(AccountDao accountdao) {
        this.accountdao = accountdao;
    }

    /**
     * 转账, 
     * @param name 转账主人
     * @param monery 多少钱
     * @param otherName 给谁
     */
    @Override
    public void transfer(String name, double monery, String otherName) {
        // TODO Auto-generated method stub

        accountdao.inMonery(name, monery);
        //int a = 100 / 0 ;
        //log.info(a+"");
        accountdao.onMonery(otherName, monery);
    }
}
4.test测试代码
package com.tx.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.tx.server.TxServer;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class PayTest {

    @Resource(name = "txserver")
    public TxServer txServer;

    @Test
    public void run(){

        /**
         * 小明给小花 30.2元
         */
        txServer.transfer("小明", 1, "小花");
    }
}
  1. spring 使用注解的方法管理事物
    1.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.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 内置的连接池:先配置连接池 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    -->


    <!-- 配置DBCP的连接池
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///spring_day03"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
     -->

    <!-- 配置C3P0的连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///mybatis"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!-- 配置JDBC的模板类 -->
    <!-- 配置平台事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 开启注解的扫描  -->
    <context:component-scan base-package="com.tx2"/>
    <!-- 开启自动代理 aop代理扫描-->
    <aop:aspectj-autoproxy/>
    <!-- 开启事务的注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="txserver" class="com.tx2.TxServeriImpl">
        <property name="accountdao" ref="accountdao"/>
    </bean>

    <bean id="accountdao" class="com.tx2.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

<!--  

这个事物是有注解的,最原始的 -->
<!-- 
    注解的方法
    事物其实就是,两条sql执行,如果一条出现了问题,另外一条就进行回滚
    比如转钱:
    小明 扣了一元
    小花就加一元
    可是在小明扣了钱以后出现了错误,
    小明的数据就必须要回滚,不然数据就会错误
 -->
2.dao层和上面的1.2一样
3.serverc层代码
package com.tx2;

import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * 在类上面添加,所有的方法都有事物管理
 * @author lenovo
 *
 */
@Transactional
public class TxServeriImpl implements TxServer {


    public void setAccountdao(AccountDao accountdao) {
        this.accountdao = accountdao;
    }

    @Autowired
    public AccountDao accountdao;

    /**
     * 转账, 
     * @param name 转账主人
     * @param monery 多少钱
     * @param otherName 给谁
     */
    @Override
    public void transfer(String name, double monery, String otherName) {
        // TODO Auto-generated method stub

        accountdao.inMonery(name, monery);
        int a = 100 / 0 ;
        //log.info(a+"");
        accountdao.onMonery(otherName, monery);
    }

    @Override
    public void selectAll() {
        // TODO Auto-generated method stub
        accountdao.selectAll();
    }


}
4.test测试
package com.tx2;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext2.xml")
public class PayTest {

    @Resource(name = "txserver")
    public TxServer txServer;

    @Test
    public void run(){

        /**
         * 小明给小花 30.2元
         */
        txServer.transfer("小明", 1, "小花");
        //txServer.selectAll();
    }
}

3.代码demo地址 https://gitee.com/yuhaifei/springJDBC.git
3.1 spring普通方法com.tx包下
3.2 spring注入的方法在com.tx2包下
3.3 com/Spring_day03.md 是黑马老师的笔记,非常感谢老师

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值