spring 事务管理 1(使用spring的JdbcTemplate访问数据库)

持久层和事务的关系

dao层脱离事务也能操作数据库,事务是保证dao层数据操作的完整性(即原子性、一致性、隔离性、持久性,也即所谓的 ACID)

事务可以保证一组操作要么全成功,要么全部失败,就是事务是一个不可分割的整体


使用spring 封装的jdbc访问数据库(未使用事务)

定义bean

package sping.jdbc;

import java.sql.SQLException;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service(value="jdbcWithoutTM")
public class JdbcWithoutTM {
   
    @Resource(name="jdbcTemplate")
    private JdbcTemplate jt;
   
  
    public void addPerson(){
        jt.execute("insert into person(pname) values ('名字')");
    }

}

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


    <context:component-scan base-package="sping.jdbc*"></context:component-scan>

    <!-- 数据源默认将autoCommit设置为true -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="${jdbc.driverClassName}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
    </bean>

    <context:property-placeholder location="jdbc.properties" />
</beans>

 

junit测试类

 package sping.jdbc.test;


import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import sping.jdbc.JdbcWithoutTM;

public class SpringJdbcTest {
    private static ApplicationContext context;
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        context = new ClassPathXmlApplicationContext(
                new String[] { "jdbc.xml" });
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Test
    public void test() {
        JdbcWithoutTM jtm=context.getBean("jdbcWithoutTM", JdbcWithoutTM.class);
        jtm.addPerson();
    }

}

此程序虽然没有配置和使用事务控制,但是数据还是插入到了数据库。这说明数据库操作并一定需要事务控制。

 现在我们修改下JdbcWithoutTM的插入方法,让他在数据库插入操作完成之后手动抛出个异常,看数据是否还能插入。

     public void addPerson(){

        jt.execute("insert into person(pname) values ('王江涛')");
        throw new RuntimeException();
    }

 

运行程序,查看数据库,结果是数据还是插入到了数据库(事务自动提交),这明显不符合我们的要求,说明此操作没有回滚,造成操作的不完整性,当然,我们只是一个插入操作,如果我们在插入操作之后再有个与之相关的数据库操作,而在两个操作中间出了个异常,那么就造成数据不完整了。

所以我们就要加入事务,而spring让我们从繁琐的事务控制中解脱出来。

我们修改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-3.0.xsd  
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-3.0.xsd  
           http://www.springframework.org/schema/aop  
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">


    <context:component-scan base-package="sping.jdbc*"></context:component-scan>

    <!-- 数据源默认将autoCommit设置为true -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="${jdbc.driverClassName}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
    </bean>

    <!-- 事务管理配置 如果使用orm框架,则替换为相应的事务管理器,注意,如果想使用注解性事务,

                        则需引入cglib-nodep.jar,不是cglib.jar-->
    <bean id="myTxManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <tx:annotation-driven transaction-manager="myTxManager"></tx:annotation-driven>

    <context:property-placeholder location="jdbc.properties" />
</beans>

在插入操作方法上面加上事务注解

    @Transactional(propagation=Propagation.REQUIRED)
    public void addPerson(){

        jt.execute("insert into person(pname) values ('王江涛')");//1
        System.out.println(1/0);//2
        jt.execute("insert into person(pname) values ('王江涛')");//3
    }

再次执行程序,可以看到,数据库并没有插入任何数据,因为程序在2处出现了异常,所以以前做的所有操作全部回滚了。这就符合我们的要求啦


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值