Spring的 JDBCTemplate和声明式事务控制

Spring 中的 JdbcTemplate[会用]

JdbcTemplate 概述

它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。spring 框架为我们提供了很多
的操作模板类。
操作关系型数据的:
JdbcTemplate
HibernateTemplate
操作 nosql 数据库的:
RedisTemplate
操作消息队列的:
JmsTemplate
我们今天的主角在 spring-jdbc-5.0.2.RELEASE.jar 中,我们在导包的时候,除了要导入这个 jar 包
外,还需要导入一个 spring-tx-5.0.2.RELEASE.jar(它是和事务相关的)。

对象的创建

我们可以参考它的源码,来一探究竟:
public JdbcTemplate() {
}
public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
setDataSource(dataSource);
setLazyInit(lazyInit);
afterPropertiesSet();
}
除了默认构造函数之外,都需要提供一个数据源。既然有set方法,依据我们之前学过的依赖注入,我们可以
在配置文件中配置这些对象。

spring 中配置数据源

bean.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">
    <context:component-scan base-package="com.itheim"/>
    <bean id="accountDao" class="com.itheim.dao.Imp.accountDaoImp">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置Jdbc-->
    <bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate" >
        <constructor-arg name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置数据源  配置 Jdbc数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/eesy"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
</beans>

配置 DBCP 数据源

导入 到工程的 lib 目录。在 spring 的配置文件中配置:
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:// /spring_day02"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>

配置C3p0数据源

导入 到工程的 lib 目录。在 spring 的配置文件中配置:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>

将数据库连接的信息配置到属性文件中:

【定义属性文件】
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_day02
jdbc.username=root
jdbc.password=123
【引入外部的属性文件】
一种方式:
<!-- 引入外部属性文件: -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
</bean>
另一种方式:
<context:property-placeholder location="classpath:jdbc.properties"/>

基本使用

public class JdbcTemplateDemo2 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
jt.execute("insert into account(name,money)values('eee',500)");
}
}

保存操作

public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
//保存
jt.update("insert into account(name,money)values(?,?)","fff",5000);
}
}

查询一个

使用 RowMapper 的方式:常用的方式
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
//查询一个
List<Account> as = jt.query("select * from account where id = ? ",
new AccountRowMapper(), 55);
System.out.println(as.isEmpty()?"没有结果":as.get(0));
}
}
用 使用 ResultSetExtractor 的方式: 不常用的方式
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
//查询一个
Account account = jt.query("select * from account where id = ?",
new AccountResultSetExtractor(),3);
System.out.println(account);
}
}

让 dao 继承 JdbcDaoSupport

JdbcDaoSupport 是spring 框架为我们提供的一个类,该类中定义了一个 JdbcTemplate 对象,我们可以
直接获取使用,但是要想创建该对象,需要为其提供一个数据源:

public class accountDaoImp extends JdbcDaoSupport implements accountDao {

    @Override
    public List<Account> saveUser() {
//        jt=new JdbcTemplate(dataSource);
        List<Account> list = super.getJdbcTemplate().query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
        if (list != null) {
            return list;
        } else {
            return null;
        }
    }


}

思考:
两版 Dao 有什么区别呢?
答案:
在 第一种在 Dao 类中定义 JdbcTemplate 的方式,适用于所有配置方式(xml 和注解都可以)。
让 第二种让 Dao 继承 JdbcDaoSupport 的方式,只能用于基于 XML

Spring 中的事务控制

第一:JavaEE 体系进行分层开发,事务处理位于业务层,Spring 提供了分层设计 业务层的事务处理解决方
案。
第二:spring 框架为我们提供了一组事务控制的接口。具体在后面的第二小节介绍。这组接口是在
spring-tx-5.0.2.RELEASE.jar 中。
第三:spring 的事务控制都是基于 AOP 的,它既可以使用编程的方式实现,也可以使用配置的方式实现。我
们学习的重点是使用配置的方式实现。

Spring 中事务控制的 API 介绍

PlatformTransactionManager
此接口是 spring 的事务管理器,它里面提供了我们常用的操作事务的方法,如下图:

我们在开发中都是使用它的实现类,如下图:
真正管理事务的对象
org.springframework.jdbc.datasource.DataSourceTransactionManager 用 使用 Spring
JDBC 或 或 iBatis 进行持久化数据时使用
org.springframework.orm.hibernate5.HibernateTransactionManager 使用
Hibernate 版本进行持久化数据时使用

TransactionDefinition
它是事务的定义信息对象,里面有如下方法:

事务的隔离级别

事务的传播行为

REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选
择(默认值)
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
NEVER:以非事务方式运行,如果当前存在事务,抛出异常
NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作。

超时时间

默认值是-1,没有超时限制。如果有,以秒为单位进行设置。

是否是只读事务

建议查询时设置为只读。

TransactionStatus

此接口提供的是事务具体的运行状态,方法介绍如下图:

基于 XML 的声明式事务控制(配置方式)

配置bean.xml步骤

<!-- 配置一个事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入 DataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>

配置事务的通知引用事务管理器

<!-- 事务的配置 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager"></tx:advice>

** 配置事务的属性**

<!--在 在 tx:advice 标签内部 配置事务的属性 -->
<tx:attributes>
<!-- 指定方法名称:是业务核心方法
read-only:是否是只读事务。默认 false,不只读。
isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
propagation:指定事务的传播行为。
timeout:指定超时时间。默认值为:-1。永不超时。
rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。
没有默认值,任何异常都回滚。
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回
滚。没有默认值,任何异常都回滚。
-->
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>

配置 AOP 切入点表达式

<!-- 配置 aop -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))"
id="pt1"/>
</aop:config>

配置切入点表达式和事务通知的对应关系

<!-- 在 在 aop:config 标签内部:建立事务的通知和切入点表达式的关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>

基于注解 的配置


开启对注解的支持

<!--开启对注解的支持-->
    <context:component-scan base-package="com.itheim"/>
    <tx:annotation-driven transaction-manager="transactionManager"/>

在业务层使用@Transactional 注解
@Transactional 配置事务的属性
该注解的属性和 xml 中的属性含义一致。该注解可以出现在接口上,类上和方法上。
出现接口上,表示该接口的所有实现类都有事务支持。
出现在类上,表示类中所有方法有事务支持
出现在方法上,表示方法有事务支持。
以上三个位置的优先级:方法>类>接口

@Service("accountService")
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class accountServiceImp implements accountService {
    @Autowired
    private accountDao accountDao;
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
    public void transfer(String sourceName, String targetName, Float money) {
        Account account= accountDao.findByAccount(sourceName);
        Account account1 = accountDao.findByAccount(targetName);
        account.setMoney(account.getMoney()-money);
        account1.setMoney(account1.getMoney()+money);
        //更新用户数据
        accountDao.updateMoney(account);
        int i=1/0;

        accountDao.updateMoney(account1);

    }
}

不使用 xml 的配置方式

@Configuration
@EnableTransactionManagement
public class SpringTxConfiguration {
//里面配置数据源,配置 JdbcTemplate,配置事务管理器。在之前的步骤已经写过了。
}

编程式业务控制(了解)

缺点:代码冗余

/**
 * 账户的业务层实现类
 *
 * 事务控制应该都是在业务层
 */
public class AccountServiceImpl implements IAccountService{

    private IAccountDao accountDao;

    private TransactionTemplate transactionTemplate;

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public Account findAccountById(Integer accountId) {
      return  transactionTemplate.execute(new TransactionCallback<Account>() {
            @Override
            public Account doInTransaction(TransactionStatus status) {
                return accountDao.findAccountById(accountId);
            }
        });
    }



    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                System.out.println("transfer....");
                //2.1根据名称查询转出账户
                Account source = accountDao.findAccountByName(sourceName);
                //2.2根据名称查询转入账户
                Account target = accountDao.findAccountByName(targetName);
                //2.3转出账户减钱
                source.setMoney(source.getMoney()-money);
                //2.4转入账户加钱
                target.setMoney(target.getMoney()+money);
                //2.5更新转出账户
                accountDao.updateAccount(source);

//                int i=1/0;

                //2.6更新转入账户
                accountDao.updateAccount(target);
                return null;
            }
        });

    }
}

bean.xml配置事务摸板

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

    <!--配置事务模板对象-->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"></property>
    </bean>
原文地址:https://www.cnblogs.com/zgrey/p/13380491.html