Tuesday 28 May 2024

Commons DbUtils tutorial

The Commons DbUtils library is a small group of tools that makes working with databases easier. When you use JDBC, you usually have to do a lot of boring, error-prone work to clean up resources. These tools handle all that cleanup for you, so you can focus on what you really want to do: getting and updating data.

 

Here are some reasons why using DbUtils is a good idea:

 

1.   No possibility for resource leaks, doing JDBC correctly isn't hard, but it takes time and can be tedious. Sometimes, connections are left open accidentally, which can cause problems. DbUtils makes sure this doesn't happen.

2.   Writing code to save data in a database becomes simpler and clearer. You need much less code, and what's left is easy to understand because it's not cluttered with resource cleanup tasks.

3.   Automatically filling in JavaBean properties from query results. You don't have to manually copy values from the database into your Java objects; DbUtils does it for you. Each row of data from the database corresponds to a Java object with all its properties already set.

 

DbUtils is not

 

1.   It's not an Object/Relational bridge. There are already many good tools for that. DbUtils is for developers who want to use JDBC without dealing with all the boring parts.

2.   It's not a Data Access Object (DAO) framework on its own, but you can use DbUtils to build one.

3.   It's not an object-oriented abstraction of database elements like tables, columns, or primary keys.

 

It's not a heavy framework of any sort. The aim of DbUtils is is to provide a simple and user-friendly JDBC helper library.

 

Dependency used for this tutorial

<dependency>
	<groupId>commons-dbutils</groupId>
	<artifactId>commons-dbutils</artifactId>
	<version>1.8.1</version>
</dependency>

 

I am using below employee table to demonstrate the examples for this tutorial series.

mysql> describe employee;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int         | YES  |     | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.18 sec)

mysql> 
mysql> 
mysql> SELECT * FROM employee;
+------+--------------+
| id   | name         |
+------+--------------+
|    1 | Hari Krishna |
|    3 | Sudhir       |
+------+--------------+
2 rows in set (0.01 sec)

 

You can download all the examples from this link.

Getting Started with Apache Commons DBUtils: A Hello World Application
Integrating Apache Commons DBUtils with DataSource
Enhancing Database Efficiency with Asynchronous Queries Using DBUtils
Mapping Result Sets to Lists with DBUtils' BeanListHandler

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment