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 ...
随机推荐
- SQL SERVER 中 实现主表1行记录,子表多行记录 整合成一条虚拟列
表中有这样的记录,简单的主子表,现要想通过left join 语句把两表关联起来 select * from tbl_diary_reback a left join tbl_diary_reback ...
- Mina入门:Java NIO基础概念
JDK1.4引入了Java NIO API(Java New IO),Java NIO得到了广泛应用.NIO允许程序进行非阻塞IO操作.java.nio.* 包括以下NIO基本结构: Buffer - ...
- JavaScript中的计时器原理
理解John Resig 在 How JavaScript Timers Work. 原理分析 timer(setInterval,setTimeout)有一个很重要的概念,时间延迟的长短是不稳定的. ...
- Git操作流水账
一.关于Git Git是一个分布式版本控制/软件配置管理软件,原是Linux内核开发者林纳斯·托瓦兹(Linus Torvalds)为更好地管理Linux内核开发而设计. 二.Git的环境配置 2.1 ...
- C# 弹出窗口查看图片以及上传图片
private void ShowSelectedPicture(string path) { FileStream fs = File.OpenRead(path); //OpenRead ; fi ...
- Java核心技术卷1Chapter7笔记 图形程序设计
Swing是指被绘制的用户界面类,AWT是指像事件处理这样的窗口工具箱的底层机制. SWT,JavaFX是可能的代替技术. 创建框架 在Java中,顶层窗口(就是没有包含在其他窗口中的窗口)被称为框架 ...
- css3实现三角形,聊天背景气泡,心形等形状
1.聊天背景气泡: css代码如下: #talkbubble {width: 120px;margin:auto; background: red; position: relative; -moz- ...
- MAC环境下生成Apple证书教程
在MAC操作系统下,生成Apple证书比较简单,全图形化操作. 一.使用Keychain Access(钥匙串访问) MAC操作系统对证书的处理都采用了“Keychain Access”(中文系统名为 ...
- warning: control reaches end of non-void function
用gcc编译一个程序的时候出现这样的警告: warning: control reaches end of non-void function 它的意思是:控制到达非void函数的结尾.就是说你的一些 ...
- FLAG_ACTIVITY_NEW_TASK和SingleInstance的设计思路(多task的应用)
这部分的想法都是基于以下两点: 1.Activity可能被复用,可能是复用Activity的功能,还可能是复用Activity的状态: 2.Task的作用:target,同一个task中的Activi ...