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 ...
随机推荐
- 个人封装的一个Camera类
好久不写博客了,代码写了不少,但大多数都是拿来主义,要不是网上,要不就是自己曾经的代码拼装. 新工作是搞Android开发的,近期任务要求我封装一个Carmera类,自己也认为还是封装以后方便使用,弄 ...
- 一个C/C++结构体初始化有趣的现象
我们知道C语言当中结构可以使用{}进行初始化,例如有结构体定义如下: typedef struct type_t { int a; int b; int c; int d; }type_t; 我们可以 ...
- setter设置器 gutter访问器
set方法书写规范: 1.必须以set开头,set后跟去掉下划线的实例变量并且首字母大写.ps: setAge:2.一定有参数3.不能有返回值4.一定是对象方法(-开头)5.形参一般是去掉下划线的实例 ...
- Web 应用配置Log4Net
1.第一步:在web.config文件添加如下代码: [sourcecode language="csharp"] <configSections> <secti ...
- java反射入门
http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html package reflectTest; class Demo{ / ...
- 开源一个监控数据采集Agent:OpenFalcon-SuitAgent
OpenFalcon-SuitAgent 项目地址:github 版本说明 本系统版本划分如下 alpha:内部测试版(不建议使用于生产环境) beta:公开测试版(不建议使用于生产环境) final ...
- jQuery1.9.1针对checkbox的调整
在jquery 1.8.x中的版本,我们对于checkbox的选中与不选中操作如下: 判断是否选中 $('#checkbox').prop('checked') 设置选中与不选中状态: $('#che ...
- hl7 java 解析
原文链接 http://blog.csdn.net/ycyangcai/article/details/6643784 Hl7引擎的目标主要是解决将数据按HL7协议的要求标准化,和标准业务的集成和不同 ...
- block 的调用 简单代码
#import <Foundation/Foundation.h> #import "Button.h" typedef int (^MySum) (int, int) ...
- J2SE知识点摘记(十三)
1. 字节流 InputStream(输入字节流)是一个定义了java流式字节流输入模式的抽象类.该类的所有方法在出错时都会引发一个IOExcepiton异常. Void close() ...