Spring4.3x教程之五事物详解

来源:互联网 发布:安卓清理软件 编辑:程序博客网 时间:2024/06/13 17:47

Spring支持事物操作,有2种方式:
1、编程式事物
就是使用TransactionTemplate进行事物的操作
2、声明式事物
就是借助AOP实现配置化事物操作
先来看看编程式事物的操作:
账户类:

public class Account {    private int id;    private String name;    private int money;    private String ipaddr;    public String getIpaddr() {        return ipaddr;    }    public void setIpaddr(String ipaddr) {        this.ipaddr = ipaddr;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getMoney() {        return money;    }    public void setMoney(int money) {        this.money = money;    }}

借助TransactionTemplate实现事物的添加
AccountDao类:

public class AccountDao extends JdbcDaoSupport{    private TransactionTemplate transactionTemplate;//事物模板    public TransactionTemplate getTransactionTemplate() {        return transactionTemplate;    }    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {        this.transactionTemplate = transactionTemplate;    }    //新增    public boolean save(Account account) {        int ct=getJdbcTemplate().update("insert into tb_account(name,money,ipaddr) values(?,?,?)", account.getName(),account.getMoney(),account.getIpaddr());        return ct>0?true:false;    }    //转账    public void transferMoney(String fromName,String toName,int money) {        //默认提交        transactionTemplate.execute(new TransactionCallbackWithoutResult() {            /*             * 开启事物执行sql             * 参数说明:             * 1、事物状态             * 因为内部默认开启了事物并且会自动提交             * 所以我们只需要验证什么时候回滚*/            @Override            protected void doInTransactionWithoutResult(TransactionStatus ts) {                // TODO Auto-generated method stub                String sql="update tb_account set money=money+? where name=?";                try {                    int ct1=getJdbcTemplate().update(sql, -money,fromName);//转出                    int ct2=getJdbcTemplate().update(sql, money,toName);//转入                    if(!(ct1==1 && ct1==ct2)){                        ts.setRollbackOnly();//回滚                    }                } catch (DataAccessException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                    ts.setRollbackOnly();//回滚                }            }        });    }    //查询    public List<Account> queryAll() {        return getJdbcTemplate().query("select * from tb_account", new RowMapper<Account>(){            @Override            public Account mapRow(ResultSet rs, int index) throws SQLException {                // TODO Auto-generated method stub                Account account=new Account();                account.setId(rs.getInt("id"));                account.setMoney(rs.getInt("money"));                account.setName(rs.getString("name"));                account.setIpaddr(rs.getString("ipaddr"));                return account;            }        });    }    //查询所有名字    public List<String> queryAllNames() {        return getJdbcTemplate().queryForList("select name from tb_account",String.class);    }}

看看applicationContet.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">    <!--Spring JDBC模块+编程式事物模块 -->    <!--加载数据库的连接配置文件 -->    <context:property-placeholder location="classpath:dbconfig.properties" />    <!--配置数据库来连接池 -->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"        destroy-method="close">        <!--驱动类全称 -->        <property name="driverClass" value="${jdbc.driverClassName}" />        <!--数据库的url地址 -->        <property name="jdbcUrl" value="${jdbc.url}" />        <!--用户名 -->        <property name="user" value="${jdbc.username}" />        <!--密码 -->        <property name="password" value="${jdbc.password}" />        <!--配置最大的连接数 -->        <property name="maxPoolSize" value="${jdbc.maxsize}"></property>        <!--配置最小的连接数 -->        <property name="minPoolSize" value="${jdbc.minsize}"></property>        <!--配置连接最大空闲时间 -->        <property name="maxIdleTime" value="${jdbc.idletime}"></property>    </bean><!--事物管理对象 -->    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource"/>    </bean>    <!--事物模板对象  -->    <bean id="tran" class="org.springframework.transaction.support.TransactionTemplate">    <constructor-arg name="transactionManager" ref="txManager"></constructor-arg>    </bean>    <!--配置dao对象 -->    <bean id="adao" class="cn.code404.dao.AccountDao" scope="prototype">        <property name="dataSource" ref="dataSource"></property>        <property name="transactionTemplate" ref="tran"></property>    </bean>    <!--配置service对象 -->    <bean id="aservice" class="cn.code404.service.AccountService" scope="prototype">        <property name="dao" ref="adao"></property>    </bean></beans>

重要的就是dao中的代码。
下面是使用的声明式事物的操作
学生类:

public class Student {    private int id;    private String name;    private String sex;    private String qq;    private String sign;    private int age;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public String getQq() {        return qq;    }    public void setQq(String qq) {        this.qq = qq;    }    public String getSign() {        return sign;    }    public void setSign(String sign) {        this.sign = sign;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public Student(String name, String sex, String qq, String sign, int age) {        super();        this.name = name;        this.sex = sex;        this.qq = qq;        this.sign = sign;        this.age = age;    }    public Student() {        super();    }}

关键看dao

public class StudentDao extends JdbcDaoSupport{    //保存    public boolean save(Student student) {        //新增语句,非查询SQL        int ct=getJdbcTemplate().update(                "insert into tb_student(name,age,sex,qq,sign) values(?,?,?,?,?)",                 student.getName(),student.getAge(),student.getSex(),student.getQq(),student.getSign());        return ct>0?true:false;    }    //查询全部    public List<Student> queryAll() {        //Class要求查询的列只能有一个        return getJdbcTemplate().query("select * from tb_student", new ResultType());    }    //模糊查询    public List<Student> queryLikeName(String name) {        return getJdbcTemplate().query("select * from tb_student where name like ?",                 new ResultType(), "%"+name+"%");    }    private class ResultType implements RowMapper<Student>{        @Override        public Student mapRow(ResultSet rs, int index) throws SQLException {            // TODO Auto-generated method stub            // TODO Auto-generated method stub            Student student=new Student(rs.getString("name"), rs.getString("sex"), rs.getString("qq"), rs.getString("sign"), rs.getInt("age"));            student.setId(rs.getInt("id"));            return student;        }    }}

这是重要的applicationContext.xml配置要是有AOP进行配置:

<?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">    <!--Spring JDBC模块+Tx声明式事物模块 -->    <!--加载数据库的连接配置文件 -->    <context:property-placeholder location="classpath:dbconfig.properties" />    <!--配置数据库来连接池 -->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"        destroy-method="close">        <!--驱动类全称 -->        <property name="driverClass" value="${jdbc.driverClassName}" />        <!--数据库的url地址 -->        <property name="jdbcUrl" value="${jdbc.url}" />        <!--用户名 -->        <property name="user" value="${jdbc.username}" />        <!--密码 -->        <property name="password" value="${jdbc.password}" />        <!--配置最大的连接数 -->        <property name="maxPoolSize" value="${jdbc.maxsize}"></property>        <!--配置最小的连接数 -->        <property name="minPoolSize" value="${jdbc.minsize}"></property>        <!--配置连接最大空闲时间 -->        <property name="maxIdleTime" value="${jdbc.idletime}"></property>    </bean><!--事物管理对象 -->    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource"/>    </bean><!--配置事物的通知  -->    <tx:advice id="txAdvice" transaction-manager="txManager">        <!-- 事物的属性,其实就是为切面中的哪些方法进行事物的配置 -->        <tx:attributes>        <!--配置切面中的方法的事物配置          propagation:事物的传播行为            通俗的说:也就是事物的创建方式,其实就是标记事物该如何创建            取值说明:            1、REQUIRED: 如果存在,使用当前事物,不存在就新建            2、REQUIRES_NEW:每次都是新建事物,如果存在,就让之前的事物挂起            3、MANDATORY:如果存在,使用当前事物,如果不存在,就抛异常            4、NESTED:嵌套事物,内部事务(当前事物)内另一个事物内部,都成功才算完成            5、NEVER:不使用事物,如果存在抛异常            6、NOT_SUPPORTED:不使用事物,如果存在就挂起            7、SUPPORTS:支持事物,如果不存在就不使用事物          isolation:隔离级别                             取值说明:              1、SERIALIZABLE串行化,可以避免:脏读、可不重复读、虚读              2、REPEATABLE_READ:避免脏读、不可重复读:mySQL默认的隔离级别              3、READ_COMMITTED:避免脏读              4、READ_UNCOMMITTED:什么都可能发生          -->        <tx:method name="save*" propagation="REQUIRED"/>        </tx:attributes>    </tx:advice>    <!--aop配置信息  -->    <aop:config>        <aop:pointcut id="pcut" expression="execution(* cn.code404.servie.*Service.*(..))"/>        <aop:advisor advice-ref="txAdvice" pointcut-ref="pcut"/>    </aop:config>    <!--配置dao对象 -->    <bean id="sdao" class="cn.code404.dao.StudentDao" scope="prototype">        <property name="dataSource" ref="dataSource"></property>    </bean>    <!--配置service对象 -->    <bean id="sservice" class="cn.code404.service.StudentService" scope="prototype">        <property name="dao" ref="sdao"></property>    </bean></beans>
原创粉丝点击