JavaWeb框架————Spring(三)

1、Spring整合JDBC

1.1 方式一(没有整合到Spring容器中的,即传统的)
Demo.java

package cn.ctgu.jdbctemplate;

import java.beans.PropertyVetoException;

import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;

import com.mchange.v2.c3p0.ComboPooledDataSource;

//演示JDBC模板
public class Demo {
    @Test
    public void fun1() throws PropertyVetoException {

        //1、准备连接池
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql:///hibernate");
        dataSource.setUser("root");
        dataSource.setPassword("123456");
        //2、创建JDBC模板对象
        JdbcTemplate jt=new JdbcTemplate();
        jt.setDataSource(dataSource);
        //3、书写sql并执行
        String sql="insert into t_user values(null,'rose')";
        jt.update(sql);
    }
}

1.2 方式二
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

代码示例
UserDao.java

package cn.ctgu.jdbctemplate;

import java.util.List;

import cn.ctgu.bean.User;

public interface UserDao {
    //增
    void save(User u);
    //删
    void delete(Integer id);
    //改
    void update(User u);
    //查
    User getById(Integer id);

    int getTotalCount();

    List<User>getAll();
}

UserDaoImpl.java

package cn.ctgu.jdbctemplate;

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



import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import cn.ctgu.bean.User;
//使用jdbc模板实现增删改查
public class UserDaoImpl implements UserDao {
    private JdbcTemplate jt;
    @Override
    public void save(User u) {
        // TODO Auto-generated method stub
        String sql="insert into t_user values(null,?)";
        jt.update(sql,u.getName());
    }

    @Override
    public void delete(Integer id) {
        // TODO Auto-generated method stub
        String sql="delete from t_user where id=?";
        jt.update(sql,id);
    }

    @Override
    public void update(User u) {
        // TODO Auto-generated method stub
        String sql="update  t_user set name=? where id=?";
        jt.update(sql,u.getName(),u.getId());
    }

    @Override
    public User getById(Integer id) {
        // TODO Auto-generated method stub
        String sql="select * from t_user where id=?";
        return jt.queryForObject(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                // TODO Auto-generated method stub
                User u=new User();
                u.setId(rs.getInt(id));
                u.setName(rs.getString("name"));
                return u;
            }},id);

    }

    @Override
    public int getTotalCount() {

        String sql="select count(*) from t_user";
        Integer count=jt.queryForObject(sql, Integer.class);

        return count;
    }

    @Override
    public List<User> getAll() {
        String sql="select count(*) from t_user";
        List<User> list=jt.query(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                // TODO Auto-generated method stub
                User u=new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }});

        return list;
    }

    public JdbcTemplate getJt() {
        return jt;
    }

    public void setJt(JdbcTemplate jt) {
        this.jt = jt;
    }

}

db.properties

jdbc.jdbcUrl=jdbc:mysql:///hibernate
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456

配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

<!--指定spring读取db.properties配置取代下面的那种传统方式  -->
<context:property-placeholder location="classpath:db.properties"/>
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
    <property name="driverClass" value="${jdbc.driverClass}"></property>
    <property name="user" value="${jdbc.user}"></property>
    <property name="password" value="${jdbc.password}"></property>
</bean>


<!-- 1、将连接池放入spring容器 -->
<!-- <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="jdbcUrl" value="jdbc:mysql:///hibernate"></property>
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="user" value="root"></property>
    <property name="password" value="123456"></property>
</bean> -->

<!-- 2、将JDBTemplate放入Spring容器  采用继承JDBCDaoSupport方法则可不要这个-->
<!-- <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>

</bean> -->

<!-- 3、将UserDao放入spring容器 -->
<!-- <bean name="userDao" class="cn.ctgu.jdbctemplate.UserDaoImpl"> -->
    <!-- <property name="jt" ref="jdbcTemplate"></property> -->

    <!--下面是继承JdbcDaoSupport的配置方式 (不需要将将JDBTemplate放入Spring容器 ) -->
    <bean name="userDao" class="cn.ctgu.jdbctemplate.UserDaoImpl2">
    <property name="dataSource" ref="dataSource"></property>
</bean>
</beans>

测试类
Demo2.java

package cn.ctgu.jdbctemplate;

import java.beans.PropertyVetoException;

import javax.annotation.Resource;

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

import com.mchange.v2.c3p0.ComboPooledDataSource;

import cn.ctgu.bean.User;

//演示JDBC模板(使用注解的方式)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo2 {
    @Resource(name="userDao")
    private UserDao ud;
    @Test
    public void fun1() throws PropertyVetoException {

        User u=new User();
        u.setName("tom");
        ud.save(u);
    }
    @Test
    public void fun2() throws PropertyVetoException {

        User u=new User();
        u.setId(2);
        u.setName("jack");
        ud.update(u);
    }
    @Test
    public void fun3() throws PropertyVetoException {

        ud.delete(2);
    }
    @Test
    public void fun4() throws PropertyVetoException {

        System.out.println(ud.getTotalCount());
    }
    @Test
    public void fun5() throws PropertyVetoException {

        System.out.println(ud.getById(1));
    }
    @Test
    public void fun6() throws PropertyVetoException {

        System.out.println(ud.getAll());
    }
}

1.3 方式三(继承JDBCDaoSupport,推荐使用这种)
这里写图片描述
这里写图片描述
UserDaoImpl2.java

package cn.ctgu.jdbctemplate;

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



import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import cn.ctgu.bean.User;
//使用jdbc模板实现增删改查,继承JdbcDaoSupport
public class UserDaoImpl2 extends JdbcDaoSupport implements UserDao {
    @Override
    public void save(User u) {
        // TODO Auto-generated method stub
        String sql="insert into t_user values(null,?)";
        super.getJdbcTemplate().update(sql,u.getName());
    }

    @Override
    public void delete(Integer id) {
        // TODO Auto-generated method stub
        String sql="delete from t_user where id=?";
        super.getJdbcTemplate().update(sql,id);
    }

    @Override
    public void update(User u) {
        // TODO Auto-generated method stub
        String sql="update  t_user set name=? where id=?";
        super.getJdbcTemplate().update(sql,u.getName(),u.getId());
    }

    @Override
    public User getById(Integer id) {
        // TODO Auto-generated method stub
        String sql="select * from t_user where id=?";
        return super.getJdbcTemplate().queryForObject(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                // TODO Auto-generated method stub
                User u=new User();
                u.setId(rs.getInt(id));
                u.setName(rs.getString("name"));
                return u;
            }},id);

    }

    @Override
    public int getTotalCount() {

        String sql="select count(*) from t_user";
        Integer count=super.getJdbcTemplate().queryForObject(sql, Integer.class);

        return count;
    }

    @Override
    public List<User> getAll() {
        String sql="select count(*) from t_user";
        List<User> list=super.getJdbcTemplate().query(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                // TODO Auto-generated method stub
                User u=new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }});

        return list;
    }


}

配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

<!--指定spring读取db.properties配置取代下面的那种传统方式  -->
<context:property-placeholder location="classpath:db.properties"/>
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
    <property name="driverClass" value="${jdbc.driverClass}"></property>
    <property name="user" value="${jdbc.user}"></property>
    <property name="password" value="${jdbc.password}"></property>
</bean>


<!-- 1、将连接池放入spring容器 -->
<!-- <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="jdbcUrl" value="jdbc:mysql:///hibernate"></property>
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="user" value="root"></property>
    <property name="password" value="123456"></property>
</bean> -->

<!-- 2、将JDBTemplate放入Spring容器  采用继承JDBCDaoSupport方法则可不要这个-->
<!-- <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>

</bean> -->

<!-- 3、将UserDao放入spring容器 -->
<!-- <bean name="userDao" class="cn.ctgu.jdbctemplate.UserDaoImpl"> -->
    <!-- <property name="jt" ref="jdbcTemplate"></property> -->

    <!--下面是继承JdbcDaoSupport的配置方式 (不需要将将JDBTemplate放入Spring容器 ) -->
    <bean name="userDao" class="cn.ctgu.jdbctemplate.UserDaoImpl2">
    <property name="dataSource" ref="dataSource"></property>
</bean>
</beans>

测试类
Demo2.java

package cn.ctgu.jdbctemplate;

import java.beans.PropertyVetoException;

import javax.annotation.Resource;

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

import com.mchange.v2.c3p0.ComboPooledDataSource;

import cn.ctgu.bean.User;

//演示JDBC模板(使用注解的方式)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo2 {
    @Resource(name="userDao")
    private UserDao ud;
    @Test
    public void fun1() throws PropertyVetoException {

        User u=new User();
        u.setName("tom");
        ud.save(u);
    }
    @Test
    public void fun2() throws PropertyVetoException {

        User u=new User();
        u.setId(2);
        u.setName("jack");
        ud.update(u);
    }
    @Test
    public void fun3() throws PropertyVetoException {

        ud.delete(2);
    }
    @Test
    public void fun4() throws PropertyVetoException {

        System.out.println(ud.getTotalCount());
    }
    @Test
    public void fun5() throws PropertyVetoException {

        System.out.println(ud.getById(1));
    }
    @Test
    public void fun6() throws PropertyVetoException {

        System.out.println(ud.getAll());
    }
}

2、Spring中的AOP事务
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
2.1 编码式
这里写图片描述
这里写图片描述

cn.ctgu.txdao包下,即dao层
AccountDao.java(接口)

package cn.ctgu.txdao;

public interface AccountDao {
    //加钱
    void increaseMoney(Integer id,Double money);
    //减钱
    void decreaseMoney(Integer id,Double money);
}

AccountDaoImpl.java

package cn.ctgu.txdao;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    @Override
    public void increaseMoney(Integer id, Double money) {

        getJdbcTemplate().update("update t_account set money=money+? where id=?", money,id);

    }

    @Override
    public void decreaseMoney(Integer id, Double money) {
        // TODO Auto-generated method stub
        getJdbcTemplate().update("update t_account set money=money-? where id=?", money,id);
    }

}

cn.ctgu.txservice包下,即service层
AccountService.java(接口)

package cn.ctgu.txservice;

public interface AccountService {
    //转账方法
    void transfer(Integer from,Integer to,Double money);
}

AccountServiceImpl.java

package cn.ctgu.txservice;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import cn.ctgu.txdao.AccountDao;
//在类上注解,表名该方法下的所有事务都采用该配置,如果要修改,只需要在下面的方法上重新注解下
//@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
public class AccountServiceImpl implements AccountService {

    private AccountDao ad;
    private TransactionTemplate tt;

    @Override
    //采用注解的方式配置事务属性
    //Spring的声明式事务管理xml方式(都得用到模板对象)
    //@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
    public void transfer(final Integer from, final Integer to, final Double money) {

                //减钱
                ad.decreaseMoney(from, money);
                /*int i=1/0;*/
                //加钱
                ad.increaseMoney(to, money);

    }


    /*手动编写代码的方式,在代码里面管理事务(使用模板对象实现事务操作)
     * @Override
    public void transfer(final Integer from, final Integer to, final Double money) {
        //TransactionTemplate已经封装好了事务

         * 1、打开事务
         * 2、调用TransactionCallbackWithoutResult匿名对象中的方法
         * 如果出现异常会自动进行捕捉
         * 3、提交事务
         * 
         * 
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus arg0) {
                // TODO Auto-generated method stub
                //减钱
                ad.decreaseMoney(from, money);
                //加钱
                ad.increaseMoney(to, money);
            }
        });


    }*/
    public void setAd(AccountDao ad) {
        this.ad = ad;
    }
    public void setTt(TransactionTemplate tt) {
        this.tt = tt;
    }



}

测试类
test.java

package cn.ctgu.txtest;

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 cn.ctgu.txservice.AccountService;

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

    @Resource(name="accountService")
    private AccountService as;
    @Test
    public void fun1() {
        as.transfer(1, 2, 100d);//因为是double型的,所以写成100d
    }
}

2.2 xml配置AOP事务
这里写图片描述
这里写图片描述

配置文件applicationContext2.xml(其他的与上面相同,除配置文件和AccountServiceImpl.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">

<!--配置事务的相关配置  -->
<!--事务核心管理器,封装了所有事务操作,依赖于连接池  -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property><!-- 这是类的依赖 -->
</bean>
<!-- 事务模板对象 -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager"></property>
</bean>

<!--配置事务的属性 -->
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!-- 通配符配置文件,只要是以save开头的服务都配置成该样 
        以方法为单位,指定方法应用什么事务属性
        isolation:隔离级别
        propagation:传播行为
        read-only:是否只读 -->


        <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
        <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
        <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
        <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
        <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
        <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
        <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
        <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>

        <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
    </tx:attributes>
</tx:advice>

<!-- 配置织入 -->
<aop:config>
    <!-- 配置切点表达式 -->
    <aop:pointcut expression="execution(* cn.ctgu.txservice.*ServiceImpl.*(.. ))" id="txPc"/>
    <!-- 配置切面=>通知+切入点 
        advice-ref:通知的名称
        pointcut-ref:切点的名称 -->

    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"/>
</aop:config>
<!--======================================================== -->


<!--操作数据库的基本配置  -->
<!--1、连接池  -->
<context:property-placeholder location="classpath:db.properties"/>
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
    <property name="driverClass" value="${jdbc.driverClass}"></property>
    <property name="user" value="${jdbc.user}"></property>
    <property name="password" value="${jdbc.password}"></property>
</bean>

<!--2、将accountDao放入spring容器 -->
<bean name="accountDao" class="cn.ctgu.txdao.AccountDaoImpl">
    <property name="dataSource" ref="dataSource"></property>
</bean>
<!--3、将accountDao放入spring容器 -->
<bean name="accountService" class="cn.ctgu.txservice.AccountServiceImpl">
    <property name="ad" ref="accountDao"></property>
    <property name="tt" ref="transactionTemplate"></property><!--将AccountServiceImpl中声明的两个对象注册进来,否则无法使用,就相当于创建对象  -->
</bean>
</beans>

AccountServiceImpl.xml

package cn.ctgu.txservice;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import cn.ctgu.txdao.AccountDao;
//在类上注解,表名该方法下的所有事务都采用该配置,如果要修改,只需要在下面的方法上重新注解下
//@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
public class AccountServiceImpl implements AccountService {

    private AccountDao ad;
    private TransactionTemplate tt;

    @Override
    //采用注解的方式配置事务属性
    //Spring的声明式事务管理xml方式(都得用到模板对象)
    //@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
    public void transfer(final Integer from, final Integer to, final Double money) {

                //减钱
                ad.decreaseMoney(from, money);
                /*int i=1/0;*/
                //加钱
                ad.increaseMoney(to, money);

    }


    /*手动编写代码的方式,在代码里面管理事务(使用模板对象实现事务操作)
     * @Override
    public void transfer(final Integer from, final Integer to, final Double money) {
        //TransactionTemplate已经封装好了事务

         * 1、打开事务
         * 2、调用TransactionCallbackWithoutResult匿名对象中的方法
         * 如果出现异常会自动进行捕捉
         * 3、提交事务
         * 
         * 
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus arg0) {
                // TODO Auto-generated method stub
                //减钱
                ad.decreaseMoney(from, money);
                //加钱
                ad.increaseMoney(to, money);
            }
        });


    }*/
    //被依赖的对象一定要在该文件中有set方法,否则无法注入,而且在applicationContext.xml中依赖对象的名称要与该文件中定义的名称一致 如 <property name="ad" ref="accountDao"></property>
     <property name="tt" ref="transactionTemplate">
    public void setAd(AccountDao ad) {
        this.ad = ad;
    }
    public void setTt(TransactionTemplate tt) {
        this.tt = tt;
    }



}

2.3 使用注解的方式进行AOP事务管理
这里写图片描述
这里写图片描述

配置文件applicationContext3.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">

<!--配置事务的相关配置  -->
<!--事务核心管理器,封装了所有事务操作,依赖于连接池  -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property><!-- 这是类的依赖 -->
</bean>
<!-- 事务模板对象 -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager"></property>
</bean>

<!--使用注解配置事务属性 -->
    <!--开启使用注解管理aop事务 -->
<tx:annotation-driven/>


<!--======================================================== -->


<!--操作数据库的基本配置  -->
<!--1、连接池  -->
<context:property-placeholder location="classpath:db.properties"/>
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
    <property name="driverClass" value="${jdbc.driverClass}"></property>
    <property name="user" value="${jdbc.user}"></property>
    <property name="password" value="${jdbc.password}"></property>
</bean>

<!--2、将accountDao放入spring容器 -->
<bean name="accountDao" class="cn.ctgu.txdao.AccountDaoImpl">
    <property name="dataSource" ref="dataSource"></property>
</bean>
<!--3、将accountDao放入spring容器 -->
<bean name="accountService" class="cn.ctgu.txservice.AccountServiceImpl">
    <property name="ad" ref="accountDao"></property>
    <property name="tt" ref="transactionTemplate"></property><!--将AccountServiceImpl中声明的两个对象注册进来,否则无法使用,就相当于创建对象  -->
</bean>
</beans>

AccountServiceImpl.java

package cn.ctgu.txservice;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import cn.ctgu.txdao.AccountDao;
//在类上注解,表名该方法下的所有事务都采用该配置,如果要修改,只需要在下面的方法上重新注解下
//@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
public class AccountServiceImpl implements AccountService {

    private AccountDao ad;
    private TransactionTemplate tt;

    @Override
    //采用注解的方式配置事务属性
    //Spring的声明式事务管理xml方式(都得用到模板对象)
    //@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
    public void transfer(final Integer from, final Integer to, final Double money) {

                //减钱
                ad.decreaseMoney(from, money);
                /*int i=1/0;*/
                //加钱
                ad.increaseMoney(to, money);

    }


    /*手动编写代码的方式,在代码里面管理事务(使用模板对象实现事务操作)
     * @Override
    public void transfer(final Integer from, final Integer to, final Double money) {
        //TransactionTemplate已经封装好了事务

         * 1、打开事务
         * 2、调用TransactionCallbackWithoutResult匿名对象中的方法
         * 如果出现异常会自动进行捕捉
         * 3、提交事务
         * 
         * 
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus arg0) {
                // TODO Auto-generated method stub
                //减钱
                ad.decreaseMoney(from, money);
                //加钱
                ad.increaseMoney(to, money);
            }
        });


    }*/
    //被依赖的对象一定要在该文件中有set方法,否则无法注入,而且在applicationContext.xml中依赖对象的名称要与该文件中定义的名称一致
    public void setAd(AccountDao ad) {
        this.ad = ad;
    }
    public void setTt(TransactionTemplate tt) {
        this.tt = tt;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值