Spring基础系列(三)

一、JDBC模板对象

Spring整合了一个可以操作数据库的对象JDBCTemplate(JBDC模板对象),该对象封装了jdbc技术,与DBUtils中的QueryRunner非常相似。
演示一下JDBCTemplate的使用:

//演示JDBC模板
public class Demo {
    @Test
    public void fun1() throws Exception {
        //0 准备连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql:///test");
        dataSource.setUser("root");
        dataSource.setPassword("666");
        //1 创建JDBC模板对象
        JdbcTemplate jt = new JdbcTemplate();
        jt.setDataSource(dataSource);
        //2 书写sql,并执行
        String sql = "insert into user values(null,'long') ";
        jt.update(sql);
    }
}

运行结果:
这里写图片描述
JDBCTemplate增删改查:
UserDao :

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:

//使用JDBC模板实现增删改查
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
    @Override
    public void save(User u) {
        String sql = "insert into t_user values(null,?) ";
        super.getJdbcTemplate().update(sql, u.getName());
    }
    @Override
    public void delete(Integer id) {
        String sql = "delete from t_user where id = ? ";
        super.getJdbcTemplate().update(sql,id);
    }
    @Override
    public void update(User u) {
        String sql = "update  t_user set name = ? where id=? ";
        super.getJdbcTemplate().update(sql, u.getName(),u.getId());
    }
    @Override
    public User getById(Integer id) {
        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 {
                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 * from t_user  ";
        List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }});
        return list;
    }
}

将其配置到Spring容器中:
依赖关系:
这里写图片描述
配置文件如下:

<?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"
       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">

    <!-- 指定spring读取db.properties配置 -->
    <context:property-placeholder location="classpath:db.properties"  />

    <!-- 1.将连接池放入spring容器 -->
    <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.将JDBCTemplate放入spring容器 -->
    <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
        <property name="dataSource" ref="dataSource" ></property>
    </bean>

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

</beans>

测试:

package jdbcTemplate;

import com.mchange.v2.c3p0.ComboPooledDataSource;
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 javax.annotation.Resource;

/**
 * Created by KPL on 2018/7/1.
 */
//演示JDBC模板
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-config.xml")
public class Demo {
    @Resource(name="userDao")
    private UserDao ud;
    @Test
    public void fun2() throws Exception{
        User u = new User();
        u.setName("naruto");
        ud.save(u);
    }
    @Test
    public void fun3() throws Exception{
        User u = new User();
        u.setId(2);
        u.setName("jack");
        ud.update(u);

    }
    @Test
    public void fun4() throws Exception{
        ud.delete(2);
    }
    @Test
    public void fun5() throws Exception{
        System.out.println(ud.getTotalCount());
    }
    @Test
    public void fun6() throws Exception{
        System.out.println(ud.getById(1));
    }
    @Test
    public void fun7() throws Exception{
        System.out.println(ud.getAll());
    }
}

运行结果:
这里写图片描述
public class UserDaoImpl extends JdbcDaoSupport继承了JdbcDaoSupport,Spring会根据连接池自动创建JDBC模板对象。也就是说不需要手动擦行间JBDC模板对象,从父类方法中直接获取即可。

String sql = "insert into t_user values(null,?) ";
super.getJdbcTemplate().update(sql, u.getName());

此时,配置文件修改成如下:

<?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"
       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">

    <!-- 指定spring读取db.properties配置 -->
    <context:property-placeholder location="classpath:db.properties"  />

    <!-- 1.将连接池放入spring容器 -->
    <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>

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

</beans>

二、Spring事务管理

关于事务部分的基础,可以看这篇博客JavaWeb基础系列(七)事务
Spring封装了事务管理的代码:打开事务、提交事务、回滚事务。
因为在不用平台,操纵事务的代码各不相同,于是Spring提供了一个接口PlatfromTransactionManager接口,针对不同的平台,提供不同的实现类。

***** 真正管理事务的对象
org.springframework.jdbc.datasource.DataSourceTransactionManager 
//使用 SpringJDBC 或 iBatis 进行持久化数据时使用
org.springframework.orm.hibernate3.HibernateTransactionManager 
//使用Hibernate 版本进行持久化数据时使用

事务的传播行为:决定业务方法之间调用,事务应该如何处理。

//保证同一个事务中
PROPAGATION_REQUIRED 支持当前事务,如果不存在 就新建一个(默认)
PROPAGATION_SUPPORTS 支持当前事务,如果不存在,就不使用事务
PROPAGATION_MANDATORY 支持当前事务,如果不存在,抛出异常
//保证没有在同一个事务中
PROPAGATION_REQUIRES_NEW 如果有事务存在,挂起当前事务,创建一个新的事务
PROPAGATION_NOT_SUPPORTED 以非事务方式运行,如果有事务存在,挂起当前事务
PROPAGATION_NEVER 以非事务方式运行,如果有事务存在,抛出异常
PROPAGATION_NESTED 如果当前事务存在,则嵌套事务执行

演示一下Spring事务:
先完成基本的转账功能:
Dao:

package Transaction.dao;

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

DaoImpl:

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) {
        getJdbcTemplate().update("update t_account set money = money-? where id = ? ", money,id);
    }
}

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"
       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">

    <!-- 指定spring读取db.properties配置 -->
    <context:property-placeholder location="classpath:db.properties"  />

    <!-- 1.将连接池 -->
    <bean name="dataSource1" 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.Dao-->
    <bean name="accountDao" class="Transaction.dao.AccountDaoImpl" >
        <property name="dataSource" ref="dataSource1" ></property>
    </bean>
    <!-- 3.Service-->
    <bean name="accountService" class="Transaction.service.AccountServiceImpl" >
        <property name="ad" ref="accountDao" ></property>
    </bean>
</beans>

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-config2.xml")
public class Demo {
    @Resource(name="accountService")
    private AccountService as;
    @Test
    public void fun1(){
        as.transfer(1, 2, 100d);
    }
}

运行结果:
这里写图片描述
现在开始加事务:
Spring管理事务的方式:
编码式:(了解)

将核心事务管理器配置到Spring容器:

<?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"
       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">

<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />

<!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
    <property name="dataSource" ref="dataSource1" ></property>
</bean>

<!-- 事务模板对象 -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
    <property name="transactionManager" ref="transactionManager" ></property>
</bean>

<!-- 1.将连接池 -->
<bean name="dataSource1" 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.Dao-->
<bean name="accountDao" class="Transaction.dao.AccountDaoImpl" >
    <property name="dataSource" ref="dataSource1" ></property>
</bean>
<!-- 3.Service-->
<bean name="accountService" class="Transaction.service.AccountServiceImpl" >
    <property name="ad" ref="accountDao" ></property>
    <property name="tt" ref="transactionTemplate" ></property>
</bean>
</beans>

ServiceImpl:

@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
public class AccountServiceImpl implements AccountService {
    private AccountDao ad ;
    private TransactionTemplate tt;
    @Override
    public void transfer(final Integer from,final Integer to,final Double money) {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus arg0) {
                //减钱
                ad.decreaseMoney(from, money);
                int i = 1/0;
                //加钱
                ad.increaseMoney(to, money);
            }
        });
    }

    public void setAd(AccountDao ad) {
        this.ad = ad;
    }

    public void setTt(TransactionTemplate tt) {
        this.tt = tt;
    }
}

测试代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-config2.xml")
public class Demo {
    @Resource(name="accountService")
    private AccountService as;
    @Test
    public void fun1(){
        as.transfer(1, 2, 100d);
    }
}

运行结果,由于加入了事务,报错之后,钱并不会转过去:
这里写图片描述
XML配置(aop)
Spring内部已经封装了事务通知方法,那么咱们只需要将它配置到业务处理上去就可以了。

<?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: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 ">

    <!-- 指定spring读取db.properties配置 -->
    <context:property-placeholder location="classpath:db.properties"  />

    <!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
    <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>
            <!-- 以方法为单位,指定方法应用什么事务属性
                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="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        </tx:attributes>
    </tx:advice>

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

    <!-- 1.将连接池 -->
    <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.Dao-->
    <bean name="accountDao" class="Transaction.dao.AccountDaoImpl" >
        <property name="dataSource" ref="dataSource" ></property>
    </bean>
    <!-- 3.Service-->
    <bean name="accountService" class="Transaction.service.AccountServiceImpl" >
        <property name="ad" ref="accountDao" ></property>
        <property name="tt" ref="transactionTemplate" ></property>
    </bean>

</beans>

注解配置(aop)

<?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: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 ">

    <!-- 指定spring读取db.properties配置 -->
    <context:property-placeholder location="classpath:db.properties"  />

    <!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
    <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.将连接池 -->
    <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.Dao-->
    <bean name="accountDao" class="Transaction.dao.AccountDaoImpl" >
        <property name="dataSource" ref="dataSource" ></property>
    </bean>
    <!-- 3.Service-->
    <bean name="accountService" class="Transaction.service.AccountServiceImpl" >
        <property name="ad" ref="accountDao" ></property>
        <property name="tt" ref="transactionTemplate" ></property>
    </bean>

</beans>

加入注解:

@Transactional(isolation= Isolation.REPEATABLE_READ,propagation= Propagation.REQUIRED,readOnly=true)
public class AccountServiceImpl implements AccountService {
    private AccountDao ad ;
    private TransactionTemplate tt;

    @Override
    @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);
    }
    public void setAd(AccountDao ad) {
        this.ad = ad;
    }

    public void setTt(TransactionTemplate tt) {
        this.tt = tt;
    }
}

测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-config4.xml")
public class Demo {
    @Resource(name="accountService")
    private AccountService as;
    @Test
    public void fun1(){
        as.transfer(1, 2, 100d);
    }
}

运行结果,由于出错,钱不会转过去:
这里写图片描述

转载请标明出处,原文地址:https://blog.csdn.net/weixin_41835916
如果觉得本文对您有帮助,请点击支持一下,您的支持是我写作最大的动力,谢谢。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41835916/article/details/80877562
今日推荐