栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring中的JDBC及事务控制

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring中的JDBC及事务控制

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(它是和事务相关的)。

JdbcTemplate 对象的创建 环境搭建

编写 spring 的配置文件



配置数据源

之前已经接触过了两个数据源,C3P0 和 DBCP。要想使用这两数据源都需要导入对应的 jar 包。

配置 C3P0 数据源







配置 DBCP 数据源







配置 spring 内置数据源

spring 框 架 也 提 供 了 一 个 内 置 数 据 源 , 我 们 也 可 以 使 用 spring 的 内 置 数 据 源 , 它 就 在
spring-jdbc-5.0.2.REEASE.jar 包中:







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

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_day02
jdbc.username=root
jdbc.password=123

一种方式:





另一种方式:

JdbcTemplate 的增删改查操作 前期准备

创建数据库:

create database spring_day02;
use spring_day02;

创建表:

create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
在 spring 配置文件中配置 JdbcTemplate



    
    
        
        
    

    

    
    
        
        
        
        
    

JdbcTemplate的最基本用法
public class JdbcTemplateDemo2 {
    public static void main(String[] args) {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取对象
        JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //3.执行操作
        jt.execute("insert into account(name,money)values('ddd',2222)");
    }

}
JdbcTemplate的增删改查操作
public class JdbcTemplateDemo3 {
    public static void main(String[] args) {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取对象
        JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //3.执行操作
        //保存
//        jt.update("insert into account(name,money)values(?,?)","eee",3333f);
        //更新
//        jt.update("update account set name=?,money=? where id=?","test",4567,7);
        //删除
//        jt.update("delete from account where id=?",8);
        //查询所有
        List accounts = jt.query("select * from account where money > ?",new AccountRowMapper(),1000f);
        //List accounts = jt.query("select * from account where money > ?",new BeanPropertyRowMapper(Account.class),1000f);
        for(Account account : accounts){
            System.out.println(account);
        }
        //查询一个
//        List accounts = jt.query("select * from account where id = ?",new BeanPropertyRowMapper(Account.class),1);
//        System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));

        //查询返回一行一列(使用聚合函数,但不加group by子句)
        


    }

    
    static class AccountRowMapper implements RowMapper {
        
        @Override
        public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
            Account account = new Account();
            account.setId(rs.getInt("id"));
            account.setName(rs.getString("name"));
            account.setMoney(rs.getFloat("money"));
            return account;
        }
    }
}

在 dao 中使用 JdbcTemplate 准备实体类
public class Account implements Serializable {

    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", money=" + money +
                '}';
    }
}
第一种方式:在 dao 中定义 JdbcTemplate
ublic interface IAccountDao {

    
    Account findAccountById(Integer accountId);

    
    Account findAccountByName(String accountName);

    
    void updateAccount(Account account);
}

public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Account findAccountById(Integer id) {
List list = jdbcTemplate.query("select * from account where id = ?
",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0);
}
@Override
public Account findAccountByName(String name) {
List list = jdbcTemplate.query("select * from account where name
= ? ",new AccountRowMapper(),name);
if(list.isEmpty()){
return null;
}
if(list.size()>1){
throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
}
return list.get(0);
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set money = ? where id = ?
",account.getMoney(),account.getId());
}
}
配置文件



















问题

思考:
此种方式有什么问题吗?
答案:
有个小问题。就是我们的 dao 有很多时,每个 dao 都有一些重复性的代码。下面就是重复代码:

private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
第二种方式:让 dao 继承 JdbcDaoSupport

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

public abstract class JdbcDaoSupport extends DaoSupport {
//定义对象
private JdbcTemplate jdbcTemplate;
//set 方法注入数据源,判断是否注入了,注入了就创建 JdbcTemplate
public final void setDataSource(DataSource dataSource) {
if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource())
{
//如果提供了数据源就创建 JdbcTemplate
this.jdbcTemplate = createJdbcTemplate(dataSource);
initTemplateConfig();
}
}
//使用数据源创建 JdcbTemplate
protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
//当然,我们也可以通过注入 JdbcTemplate 对象
public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
initTemplateConfig();
}
//使用 getJdbcTmeplate 方法获取操作模板对象
public final JdbcTemplate getJdbcTemplate() {
return this.jdbcTemplate;
}
public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer id) {
//getJdbcTemplate()方法是从父类上继承下来的。
List list = getJdbcTemplate().query("select * from account where
id = ? ",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0);
}
@Override
public Account findAccountByName(String name) {
//getJdbcTemplate()方法是从父类上继承下来的。
List list = getJdbcTemplate().query("select * from account where
name = ? ",new AccountRowMapper(),name);
if(list.isEmpty()){
return null;
}
if(list.size()>1){
throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
}
return list.get(0);
}
@Override
public void updateAccount(Account account) {
//getJdbcTemplate()方法是从父类上继承下来的。
getJdbcTemplate().update("update account set money = ? where id = ?
",account.getMoney(),account.getId());
}
}
配置文件:















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

Spring 中的事务控制 Spring 中的事务控制

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

Spring 中事务控制的 API 介绍 PlatformTransactionManager

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

 
TransactionStatus getTransaction(TransactionDefinition definition)

void commit(TransactionStatus status) 
  
void rollback(TransactionStatus status) 

我们在开发中都是使用它的实现类,如下图:

TransactionDefinition

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

事务的隔离级别

事务的传播行为

超时时间

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

是否是只读事务

建议查询时设置为只读。

TransactionStatus

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

基于 XML 的声明式事务控制(配置方式) 环境搭建 第一步:拷贝必要的 jar 包到工程的 lib 目录

第二步:创建 spring 的配置文件并导入约束

此处需要导入 aop 和 tx 两个名称空间




第三步:准备数据库表和实体类 第四步:编写业务层接口和实现类
public interface IAccountService {

Account findAccountById(Integer id);//查

void transfer(String sourceName,String targeName,Float money);//增删改
}
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
public void transfer(String sourceName, String targeName, Float money) {
//1.根据名称查询两个账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName);
//2.修改两个账户的金额
source.setMoney(source.getMoney()-money);//转出账户减钱
target.setMoney(target.getMoney()+money);//转入账户加钱
//3.更新两个账户
accountDao.updateAccount(source);
int i=1/0;
accountDao.updateAccount(target);
}
}
第五步:编写 Dao 接口和实现类
public interface IAccountDao {

    
    List findAllAccount();

    
    Account findAccountById(Integer accountId);

    
    void saveAccount(Account account);

    
    void updateAccount(Account account);

    
    void deleteAccount(Integer acccountId);

    
    Account findAccountByName(String accountName);
}
public class AccountDaoImpl implements IAccountDao {

    private QueryRunner runner;
    private ConnectionUtils connectionUtils;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    @Override
    public List findAllAccount() {
        try{
            return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try{
            return runner.query(connectionUtils.getThreadConnection(),"select * from account where id = ? ",new BeanHandler(Account.class),accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try{
            runner.update(connectionUtils.getThreadConnection(),"insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try{
            runner.update(connectionUtils.getThreadConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try{
            runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountByName(String accountName) {
        try{
            List accounts = runner.query(connectionUtils.getThreadConnection(),"select * from account where name = ? ",new BeanListHandler(Account.class),accountName);
            if(accounts == null || accounts.size() == 0){
                return null;
            }
            if(accounts.size() > 1){
                throw new RuntimeException("结果集不唯一,数据有问题");
            }
            return accounts.get(0);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
第六步:在配置文件中配置业务层和持久层



    
    
        
        
    

    
    
        
        
        
        
    

    
    

    
    
        
        
        
        
        
    

    
    
        
        
    

    
    
        
        
    

    
    
        
        
        
            
            
            
            
            
            
            
            
        
    

基于注解的配置方式 环境搭建 第一步:拷贝必备的 jar 包到工程的 lib 目录

第二步:创建 spring 的配置文件导入约束并配置扫描的包



    
    


    
    

    
    
        
        
        
        
        
    



   
    

第三步:创建数据库表和实体类 第四步:创建业务层接口和实现类并使用注解让 spring 管理
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
//其余代码和基于 XML 的配置相同
}
第五步:创建 Dao 接口和实现类并使用注解让 spring 管理
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
//其余代码和基于 XML 的配置相同
}
配置步骤 第一步:配置事务管理器并注入数据源




第二步:在业务层使用@Transactional 注解
@Service("accountService")
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public void transfer(String sourceName, String targeName, Float money) {
//1.根据名称查询两个账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName);
//2.修改两个账户的金额
source.setMoney(source.getMoney()-money);//转出账户减钱
target.setMoney(target.getMoney()+money);//转入账户加钱
//3.更新两个账户
accountDao.updateAccount(source);
//int i=1/0;
accountDao.updateAccount(target);
}
}
该注解的属性和 xml 中的属性含义一致。该注解可以出现在接口上,类上和方法上。
出现接口上,表示该接口的所有实现类都有事务支持。
出现在类上,表示类中所有方法有事务支持
出现在方法上,表示方法有事务支持。
以上三个位置的优先级:方法>类>接口
第三步:在配置文件中开启 spring 对注解事务的支持


不使用 xml 的配置方式
@Configuration
@EnableTransactionManagement
public class SpringTxConfiguration {
//里面配置数据源,配置 JdbcTemplate,配置事务管理器。在之前的步骤已经写过了。
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/981038.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号