使用 JDBC 进行数据库操作需要研发人员对数据库连接、结果集等资源进行管理,对于数据库连接的获取、预加载对象、结果集对象映射转换等内容进行大量的重复性的工作,且使用过程中容易出现资源泄露问题。实际上使用 JDBC 进行数据库操作的模式都是一样的,于是就有好事者(褒义)对该系列过程进行封装,这类封装好的框架,比较出名的就是 commons-dbutils。
http://commons.apache.org/proper/commons-dbutils/
commons-dbutils 对 JDBC 进行了简要的封装,将一些通用的过程进行了简化。对比于 JDBC ,commons-dbutils 减少了数据库资源相关的管理操作,使研发人员更多的开始偏向业务开发。
The Commons DbUtils library is a small set of classes designed to make working with JDBC easier. JDBC resource cleanup code is mundane, error prone work so these classes abstract out all of the cleanup tasks from your code leaving you with what you really wanted to do with JDBC in the first place: query and update data.
运行环境:Win10 + Jdk1.8 + Maven3 + Intellij IDEA 2020 + mysql5.7
1、示例代码地址
https://gitee.com/lif/study-mybatis/tree/master
2、目录结构如下
3、pom.xml 文件引入依赖包
study-mybatis
com.ddpyjqtd
1.0-SNAPSHOT
4.0.0
simple-dbutils
simple-dbutils
UTF-8
1.8
1.8
org.projectlombok
lombok
1.18.10
provided
commons-dbutils
commons-dbutils
1.7
mysql
mysql-connector-java
8.0.20
org.slf4j
slf4j-api
1.7.30
org.apache.logging.log4j
log4j-slf4j-impl
2.13.3
test
org.apache.logging.log4j
log4j-api
2.13.3
org.apache.logging.log4j
log4j-core
2.13.3
junit
junit
4.11
test
4、增加 model 类: Demo.java
package com.ddpyjqtd.demo.jdbc.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Date;
/***
* 测试表对应的demo类
*
* @author ddpyjqtd
* @date 2020/5/27 21:54
*/
@Getter
@Setter
@ToString
public class Demo {
/**
* int 类型字段
*/
private int demoInt;
/**
* String 类型字段
*/
private String demoVarchar;
/**
* text 类型字段
*/
private String demoText;
/**
* datetime 类型字段
*/
private Date demoDateTime;
}
5、增加数据库配置文件:db.properties,内容如下:
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username=root
password=root
6、增加日志配置文件 log4j2.xml,内容如下:
d://logs
simple-dbutils
${file_path}/${project_name}.log
${file_path}/${project_name}-sql.log
${file_path}/${project_name}-error.log
%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %c{36} %L %M - %m%n
7、增加数据库配置文件读取工具类:DbUtils.java,内容如下:
package com.ddpyjqtd.demo.dbutils.utils;
import lombok.extern.slf4j.Slf4j;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;
/**
* 数据库工具类
*
* @author: ddpyjqtd
* @date: 2020/5/27 22:10
*/
@Slf4j
public class DbUtils {
private DbUtils() {
}
public static final String DRIVER;
public static final String URL;
public static final String USER_NAME;
public static final String PASS_WORD;
static {
ResourceBundle bundle = ResourceBundle.getBundle("db");
DRIVER = bundle.getString("driver");
URL = bundle.getString("url");
USER_NAME = bundle.getString("username");
PASS_WORD = bundle.getString("password");
}
/**
* 获取数据库连接
*
* @return java.sql.Connection
* @author ddpyjqtd
* @date 2020/5/28 23:36
*/
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USER_NAME, PASS_WORD);
} catch (ClassNotFoundException | SQLException e) {
log.error("getConnection error : ", e);
}
return conn;
}
}
8、编写数据库操作类:DemoDao.java,内容如下:
package com.ddpyjqtd.demo.dbutils.dao;
import com.ddpyjqtd.demo.dbutils.model.Demo;
import com.ddpyjqtd.demo.dbutils.utils.DbUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import java.sql.SQLException;
/**
* dbuitls 方式操作数据库的 dao 层
*
* @author: ddpyjqtd
* @date: 2020/5/28 23:20
*/
@Slf4j
public class DemoDao {
/**
* 通过主键获取demo对象
*
* @param demoInt demo 的主键
* @return com.ddpyjqtd.demo.dbutils.model.Demo
* @author ddpyjqtd
* @date 2020/5/28 23:28
*/
public Demo findDemoByKey(int demoInt) {
QueryRunner queryRunner = new QueryRunner();
Demo demo = null;
try {
demo = queryRunner.query(DbUtils.getConnection(), "select * from demo where demo_int = ?",
new BeanHandler<>(Demo.class, new BasicRowProcessor(new GenerousBeanProcessor())), demoInt);
} catch (SQLException e) {
log.error("query info error : ", e);
}
if (demo != null) {
log.info("demo info is : {}", demo.toString());
}
return demo;
}
}
9、执行 SQL
CREATE TABLE demo (
demo_int int(255) NOT NULL COMMENT 'int 类型字段',
demo_varchar varchar(255) NULL DEFAULT NULL COMMENT 'String 类型字段',
demo_text text NULL COMMENT 'text 类型字段',
demo_date_time datetime(0) NULL DEFAULT NULL COMMENT 'datetime 类型字段',
PRIMARY KEY (demo_int) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin COMMENT = '示例表,各个字段为数据库的各种类型' ROW_FORMAT = Dynamic;
insert into demo (demo_int, demo_varchar, demo_text, demo_date_time)
VALUES (1, 'this is demo_varchar', 'this is demo_text', now());
10、编写测试类:TestDemoDao.java,内容如下:
package com.ddpyjqtd.demo.dbutils.dao;
import com.ddpyjqtd.demo.dbutils.model.Demo;
import org.junit.Assert;
import org.junit.Test;
/**
* 测试类
*
* @author: ddpyjqtd
* @date: 2020/5/28 23:43
*/
public class TestDemoDao {
/**
* 测试查询方法
*
* @author ddpyjqtd
* @date 2020/5/28 23:45
*/
@Test
public void testFindDemoByKey() {
int demoInt = 1;
DemoDao dao = new DemoDao();
Demo demo = dao.findDemoByKey(demoInt);
Assert.assertNotNull(demo);
}
}
11、运行测试类,执行结果如下: