这次的学习重点是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案例(完成对账户表的增删改查)
步骤分析
- 准备数据库环境
- 创建java项目,导入坐标
- 编写Account实体类
- 编写AccountDao接口和实现类
- 编写AccountService接口和实现类
- 编写spring核心配置文件 (重点)
- 编写测试代码
实现
- 准备数据库
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 {
pri