spring (2) DbUtils(IOC实战)

本文详细介绍了如何将Apache的DbUtils与Spring进行XML整合,以实现数据库的CRUD操作。通过创建Account实体、编写Dao接口和实现类、Service接口和实现类,以及配置Spring核心XML文件,最后进行了测试和优化,将JDBC配置抽离到单独的文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这次的学习重点是Spring的xml整合DbUtils

DbUtils

DbUtils是Apache的一款用于简化Dao代码的工具类,它底层封装了JDBC技术
核心对象

QueryRunner queryRunner = new QueryRunner(DataSource dataSource);

核心方法

int update(); 执行增、删、改语句 

T query(); 执行查询语句 
	ResultSetHandler<T> 这是一个接口,主要作用是将数据库返回的记录封装到实体对象

举个例子
查询数据库所有账户信息到Account实体中

public class DbUtilsTest { 

	@Test 
	public void findAllTest() throws Exception { 
	// 创建DBUtils工具类,传入连接池 
	QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource()); 
	// 编写sql 
	String sql = "select * from account"; 
	// 执行sql 
	List<Account> list = queryRunner.query(sql, new BeanListHandler<Account> (Account.class));//多条记录封装成一个个Account,一个个Account最终封装成List进行返回 
	// 打印结果 
	for (Account account : list) { 
	System.out.println(account); 
	} 
} }

整合其实就是把new的事情都让spring来做

Spring的xml整合DbUtils

需求:基于Spring的xml配置实现账户的CRUD案例(完成对账户表的增删改查)
步骤分析

  1. 准备数据库环境
  2. 创建java项目,导入坐标
  3. 编写Account实体类
  4. 编写AccountDao接口和实现类
  5. 编写AccountService接口和实现类
  6. 编写spring核心配置文件 (重点)
  7. 编写测试代码

实现

  1. 准备数据库
CREATE DATABASE `spring_db`; 

USE `spring_db`; 

CREATE TABLE `account` ( 
	`id` int(11) NOT NULL AUTO_INCREMENT, 
	`name` varchar(32) DEFAULT NULL, 
	`money` double DEFAULT NULL, 
	PRIMARY KEY (`id`) 
) ; 

insert into `account`(`id`,`name`,`money`) values (1,'tom',1000), (2,'jerry',1000);

在这里插入图片描述
2. 创建java项目,导入坐标
3. 编写Account实体类

public class Account {
    private Integer id;
    private String name;
    private Double money;
}

  1. 编写AccountDao接口和实现类
public interface AccountDao {
    public List<Account> findAll(); 
    
    public Account findById(Integer id); 
    
    public void save(Account account); 
    
    public void update(Account account);
    
    public void delete(Integer id);
}

把QueryRunner对象交给spring去创建,当需要用到时在去IOC容器中获取

public class AccountDapImpl implements AccountDao {

    private QueryRunner queryRunner;
    //表示用set方法把queryRunner注入进来并赋值给成员变量
    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    @Override
    public List<Account> findAll() {
        List<Account> list = null;
        // 编写sql
        String sql = "select * from account";

        try {
            //执行SQL
            list = queryRunner.query(sql, new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }

    @Override
    public Account findById(Integer id) {
        Account account = null;
        // 编写sql
        String sql = "select * from account where id = ?";
        // 执行sql
        try {
            account = queryRunner.query(sql, new BeanHandler<Account>(Account.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return account;
    }

    @Override
    public void save(Account account) {
        // 编写sql
        String sql = "insert into account values(null,?,?)";
        // 执行sql
        try {
            queryRunner.update(sql, account.getName(), account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(Account account) {
        // 编写sql
        String sql = "update account set name = ?,money = ? where id = ?";
        // 执行sql
        try {
            queryRunner.update(sql, account.getName(), account.getMoney(),account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(Integer id) {
        // 编写sql
        String sql = "delete from account where id = ?";
        // 执行sq
        try {
            queryRunner.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
  1. 编写AccountService接口和实现类
public interface AccountService {

    public List<Account> findAll();

    public Account findById(Integer id);

    public void save(Account account);

    public void update(Account account);

    public void delete(Integer id);
}

public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;

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

    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }

    @Override
    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

    @Override
    public void save(Account account) {
        accountDao.save(account);
    }

    @Override
    public void update(Account account) {
        accountDao.update(account);
    }

    @Override
    public void delete(Integer id) {
        accountDao.delete(id);
    }
}

6.编写spring核心配置文件
即配置一些bean标签

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

    <!--把数据库连接池交给IOC容器-->
    <!--配置数据源对象dataSource-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_db"/>
        <property name="username" value="root"/>
        <property name="password" value="hmyhmy"/>
    </bean>

    <!--queryRunner-->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>

    <!--AccountDao-->
    <bean id="accountDao" class="com.lagou.dao.impl.AccountDapImpl">
        <property name="queryRunner" ref="queryRunner"/>
    </bean>


    <!--AccountService-->
    <bean id="accountService" class="com.lagou.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>


</beans>

7.编写测试代码

8.优化:抽取jdbc配置文件

在这里插入图片描述
applicationContext中也要引入jdbc.properities文件

* 命名空间: xmlns:context="http://www.springframework.org/schema/context" 

* 约束路径: 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd

${}就是EL表达式

<context:property-placeholder location="classpath:jdbc.properties"/>

    <!--把数据库连接池交给IOC容器-->
    <!--配置数据源对象dataSource-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值