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:

  1. No possibilities for resource leak.
  2. Cleaner, clearer persistence code. The amount of code needed to persist data in a database is drastically reduced.
  3. 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.

  1. BeanHandler: It converts the ResultSet row into a JavaBean.
  2. MapHandler: It converts the ResultSet row into a Map.
  3. 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的更多相关文章

  1. java JDBC (七) org.apache.commons.dbutils 查询

    package cn.sasa.demo1; import java.sql.Connection; import java.sql.SQLException; import java.util.Li ...

  2. java JDBC (六) org.apache.commons.dbutils 增删改

    dbutils是apache封装了JDBC的工具类,比mysql-connector更方便些 下载地址:http://commons.apache.org/proper/commons-dbutils ...

  3. Java连接数据库 #04# Apache Commons DbUtils

    索引 通过一个简单的调用看整体结构 Examples 修改JAVA连接数据库#03#中的代码 DbUtils并非是什么ORM框架,只是对原始的JDBC进行了一些封装,以便我们少写一些重复代码.就“用” ...

  4. java.lang.ClassNotFoundException: org.apache.commons.dbutils.QueryRunner

    七月 28, 2017 11:06:33 下午 org.apache.catalina.core.StandardWrapperValve invoke严重: Servlet.service() fo ...

  5. Java学习之DBUtils工具的学习

    简介 commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影 ...

  6. Apache Commons DbUtils 快速上手

    原文出处:http://lavasoft.blog.51cto.com/62575/222771 Hibernate太复杂,iBatis不好用,JDBC代码太垃圾,DBUtils在简单与优美之间取得了 ...

  7. 写一个ORM框架的第一步(Apache Commons DbUtils)

    新一次的内部提升开始了,如果您想写一个框架从Apache Commons DbUtils开始学习是一种不错的选择,我们先学习应用这个小“框架”再把源代码理解,然后写一个属于自己的ORM框架不是梦. 一 ...

  8. Java的commons包的简介

    Jakarta Commons是Jakarta的一个子项目,目的是创建和维护独立于其他框架和产品的程序包(packages).Jakarta Commons项目源于重用,其中的程序包必须确保能够重用. ...

  9. java的Commons包简介

    http://mxdxm.iteye.com/blog/758453 Jakarta Commons是Jakarta的一个子项目,目的是创建和维护独立于其他框架和产品的程序包(packages).Ja ...

  10. Java数据库小项目02--管家婆项目

    目录 项目要求 开发环境搭建 工具类JDBCUtils 创建管家婆数据表 项目分层 MainApp层 MainView层 ZhangWuController层 ZhangWuService层 Zhan ...

随机推荐

  1. MVC中使用AuthorizeAttribute做身份验证操作【转】

    http://blog.csdn.net/try530/article/details/7782704 代码顺序为:OnAuthorization-->AuthorizeCore-->Ha ...

  2. CSS3 border属性的妙用

    .ribbon { background: #45c9c8; position: absolute; width: 75px; height: 25px; line-height: 25px; top ...

  3. c# 借助cmd命令解析apk文件信息

    借助aapt.exe文件 aapt.exe 解析apk包信息cmd命令: aapt dump badging *.apkaapt d badging *.apk >1.txt(保存成1.txt文 ...

  4. Objective-c开发教程--MRC和ARC混编

    iOS5.0以后就开始可以使用ARC来代替之前的MRC. 1.ARC中使用MRC的类.方法如下: 在targets的build phases选项下Compile Sources下选择要不使用arc编译 ...

  5. iOS7、iOS8推送通知的区别

    iOS8版本以后的推送通知代码[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificati ...

  6. windows下的mongodb下载安装

    1.首先从官网https://www.mongodb.org/下载mongodb的安装包,本人下载的是mongoDB3.2版本的.msi的文件,然后双击安装即可 2.点击next 3.compelte ...

  7. CCF计算机认证——字符串匹配问题(运行都正确,为什么提交后只给50分?)

    我的程序: #include<iostream> #include<cctype> #include<string> #include<vector> ...

  8. Linux学习之/etc/init.d/functions详解

    转自:http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=28773997&id=3996557 /etc/init.d/f ...

  9. NodeJS爬虫系统初探

    NodeJS爬虫系统 NodeJS爬虫系统 0. 概论 爬虫是一种自动获取网页内容的程序.是搜索引擎的重要组成部分,因此搜索引擎优化很大程度上是针对爬虫而做出的优化. robots.txt是一个文本文 ...

  10. GO语言搭建

    最近对GO语言产生了浓厚的兴趣.因为GO语言不仅仅可以开发桌面.web程序,最吸引我的是安卓大有往GO语言全方位靠拢的趋势,自家的系统还是用自家的语言开发比较靠谱. 用一句话来说:Go语言是谷歌200 ...