java——数据库——commons-DbUtils
Apache Commons DbUtils Tutorial
The Apache 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.
Advantages of Using DbUtils are:
- No possibilities for resource leak.
- Cleaner, clearer persistence code. The amount of code needed to persist data in a database is drastically reduced.
- Automatically populate JavaBean properties from ResultSets. You don’t need to manually copy column values into bean instances by calling setter methods. Each row of the ResultSet can be represented by one fully populated bean instance.
The main classes used from this DbUtils library are DbUtils, QueryRunner and the ResultSetHandler.
DbUtils: A collection of JDBC helper methods, all the methods in this class are static, and this class is a thread safe means multiple threads can access concurrently.
ResultSetHandler: It is an interface, implementations of this interface convert ResultSets into other objects.
- BeanHandler: It converts the ResultSet row into a JavaBean.
- MapHandler: It converts the ResultSet row into a Map.
- BeanListHandler: It converts a ResultSet into a List of beans. etc
QueryRunner: Executes SQL queries with pluggable strategies for handling ResultSets. This class is thread safe.
Simple example to use DbUtils, QueryRunner and ResultSetHandler:
1. The User table, here is the script to create the database table and inserting the data into the User table.
CREATE TABLE IF NOT EXISTS `user` (
`userId` int(11) NOT NULL AUTO_INCREMENT,
`firstName` varchar(50) NOT NULL,
`lastName` varchar(50) NOT NULL,
`phoneNo` varchar(50) NOT NULL,
`emailId` varchar(50) NOT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB; INSERT INTO `user` (`userId`, `firstName`, `lastName`, `phoneNo`, `emailId`) VALUES
(1, 'Pramod', 'Ganta', '', 'pramod@codesuggestions.com'),
(2, 'Suman', 'Manthena', '', 'suman@codesuggestions.com'),
(3, 'Prakash', 'Puli', '', 'prakash@codesuggestions.com'),
(4, 'Rohit', 'Sunkari', '', 'rohit@codesuggestions.com');
2. The Java Bean class representing the User table. The property name are same as the column names in User table.
package db.utisl2; public class User {
private String userId;
private String firstName;
private String lastName;
private String phoneNO;
private String emailId; public User() {
} public String getUserId() {
return userId;
} public void setUserId(String userId) {
this.userId = userId;
} public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getPhoneNO() {
return phoneNO;
} public void setPhoneNO(String phoneNO) {
this.phoneNO = phoneNO;
} public String getEmailId() {
return emailId;
} public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
3. In this example class using BeanHandler which is the implementation of the ResultSetHandler interface, and it returns the ResultSet into a Java Bean Object.
package db.utisl2; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler; public class DbUtilsBeanHandler {
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/test";
String driver = "com.mysql.jdbc.Driver";
String usr = "root";
String pwd = "root";
User user = null;
try {
// Loading the Driver using DbUtils static method
DbUtils.loadDriver(driver);
conn = DriverManager.getConnection(url, usr, pwd);
QueryRunner query = new QueryRunner();
user = query.query(conn, "select * from user where userId=3", new BeanHandler<User>(
User.class));
// query.query
System.out.println("User Object:: " + user.getUserId() + "\t" + user.getFirstName()
+ "\t" + user.getLastName() + "\t" + user.getEmailId()); } catch (SQLException se) {
se.printStackTrace();
} finally {
// Closing the connection quietly, means it will handles the
// SQLException
DbUtils.closeQuietly(conn);
}
}
}
Output:
User Object:: 3 Prakash Puli
4. In this example class using BeanListHandler which also the implementation of the ResultSetHandler interface, and it returns the ResultSet into a List of Java Bean Objects.
package db.utisl2; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler; public class DbUtilsBeanListHandler { public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/test";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pwd = "root";
List<User> users = null;
try {
DbUtils.loadDriver(driver);
conn = DriverManager.getConnection(url, user, pwd);
QueryRunner query = new QueryRunner();
users = query.query(conn, "select * from user", new BeanListHandler<User>(User.class));
for (int i = 0; i < users.size(); i++) {
User bean = users.get(i);
System.out.println("User Objects:: " + bean.getUserId() + "\t"
+ bean.getFirstName() + "\t" + bean.getLastName() + "\t"
+ bean.getEmailId());
}
} catch (SQLException se) {
se.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
}
Output:
User Objects:: 1 Pramod Ganta pramod@codesuggestions.com
User Objects:: 2 Suman Manthena suman@codesuggestions.com
User Objects:: 3 Prakash Puli prakash@codesuggestions.com
User Objects:: 4 Rohit Sunkari rohit@codesuggestions.com
5. In this example class using MapListHandler which also the implementation of the ResultSetHandler interface, and it returns the ResultSet into a List of Map Objects. The Map object contains the each row, the column name as key and value as value in the Map object.
package db.utisl2; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler; public class DbUtilsMapListHandler { public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/test";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pwd = "root";
try {
DbUtils.loadDriver(driver);
conn = DriverManager.getConnection(url, user, pwd);
QueryRunner query = new QueryRunner();
List<Map<String, Object>> mapList = query.query(conn, "select * from user",
new MapListHandler());
for (int i = 0; i < mapList.size(); i++) {
Map<String, Object> map = mapList.get(i);
System.out.println("------> " + map.get("userId") + "\t" + map.get("firstName")
+ "\t" + map.get("emailId"));
}
} catch (SQLException se) {
se.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
}
Output:
------> 1 Pramod pramod@codesuggestions.com
------> 2 Suman suman@codesuggestions.com
------> 3 Prakash prakash@codesuggestions.com
------> 4 Rohit rohit@codesuggestions.com
Note: When we fetching from the Map, if we give the wrong column name it ruturn null value. Ex: map.get("fistName"), here mispelling the firstName. The same with BeanHandler to, if the Bean properties and table columns are not in match, it will return null values.
java——数据库——commons-DbUtils的更多相关文章
- java JDBC (七) org.apache.commons.dbutils 查询
package cn.sasa.demo1; import java.sql.Connection; import java.sql.SQLException; import java.util.Li ...
- java JDBC (六) org.apache.commons.dbutils 增删改
dbutils是apache封装了JDBC的工具类,比mysql-connector更方便些 下载地址:http://commons.apache.org/proper/commons-dbutils ...
- Java连接数据库 #04# Apache Commons DbUtils
索引 通过一个简单的调用看整体结构 Examples 修改JAVA连接数据库#03#中的代码 DbUtils并非是什么ORM框架,只是对原始的JDBC进行了一些封装,以便我们少写一些重复代码.就“用” ...
- java.lang.ClassNotFoundException: org.apache.commons.dbutils.QueryRunner
七月 28, 2017 11:06:33 下午 org.apache.catalina.core.StandardWrapperValve invoke严重: Servlet.service() fo ...
- Java学习之DBUtils工具的学习
简介 commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影 ...
- Apache Commons DbUtils 快速上手
原文出处:http://lavasoft.blog.51cto.com/62575/222771 Hibernate太复杂,iBatis不好用,JDBC代码太垃圾,DBUtils在简单与优美之间取得了 ...
- 写一个ORM框架的第一步(Apache Commons DbUtils)
新一次的内部提升开始了,如果您想写一个框架从Apache Commons DbUtils开始学习是一种不错的选择,我们先学习应用这个小“框架”再把源代码理解,然后写一个属于自己的ORM框架不是梦. 一 ...
- Java的commons包的简介
Jakarta Commons是Jakarta的一个子项目,目的是创建和维护独立于其他框架和产品的程序包(packages).Jakarta Commons项目源于重用,其中的程序包必须确保能够重用. ...
- java的Commons包简介
http://mxdxm.iteye.com/blog/758453 Jakarta Commons是Jakarta的一个子项目,目的是创建和维护独立于其他框架和产品的程序包(packages).Ja ...
- Java数据库小项目02--管家婆项目
目录 项目要求 开发环境搭建 工具类JDBCUtils 创建管家婆数据表 项目分层 MainApp层 MainView层 ZhangWuController层 ZhangWuService层 Zhan ...
随机推荐
- 给自己保存份CSS初始值样式
@charset "utf-8";body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,text ...
- TCP慢启动算法
慢启动定义 慢启动,是传输控制协议使用的一种阻塞控制机制.慢启动也叫做指数增长期.慢启动是指每次TCP接收窗口收到确认时都会增长.增加的大小就是已确认段的数目.这种情况一直保持到要么没有收到一些段,要 ...
- oracle11g+ef+vs2013做的项目在部署的时候碰到的问题
最近公司做一个项目,用到了ef和oracle11g,开发工具用的是vs2013,开发完成后,在本机上完美运行,但是,当到了要到服务器上部署的时候,就出了问题,服务器环境是server08R2,开发环境 ...
- 使用EXTEND方式来分段处理大表的搬数据
创建一个表: 记录rowid的分区段并作为处理的日志表: DROP TABLE DEAL_TABLE_EXTENT; CREATE TABLE DEAL_TABLE_EXTENT(seq ...
- DOM缘起
DOM是现在按W3C标准的浏览器均实现的标准.HTML.CSS.DOM共同在结构.表现.交互上共同支撑起一个页面.当然,必须以用户为中心.平稳退化.逐渐增强.DOM的操作是通过JS来实现的.JS最初在 ...
- statistics specify some columns count
# -k1 follow the first column nr
- js 中 setTimeout()的用法
setTimeout()在js类中的使用方法 setTimeout (表达式,延时时间)setTimeout(表达式,交互时间)延时时间/交互时间是以豪秒为单位的(1000ms=1s) setTi ...
- mud目录命令说明
目錄結構 以下列出的是 ES2 mudlib 根目錄下標準的子目錄結構,以及簡短的說明. /adm 儲存由系統管理者所管理的程式與資料檔. /std 儲存標準物件的程式碼. /obj 儲存通用物件 ...
- jira 解决结果配置
jira 的配置比较繁琐,有很多的小细节,使用中出现了各种小问题,总结梳理下 1.解决结果 问题1:编辑了任务后,解决结果变成了已解决 找到编辑任务所对应的界面方案,将解决结果字段从界面配置里移除 问 ...
- hdu 5724 Chess 博弈
题目链接 一个n行20列的棋盘. 每一行有若干个棋子. 两人轮流操作, 每人每次可以将一个棋子向右移动一个位置, 如果它右边有一个棋子, 就跳过这个棋子, 如果有若干个棋子, 就将这若干个都跳过. 但 ...