Skip to content

Commit 9c643cd

Browse files
juarezjaramilloyetanotherallisonf
authored andcommitted
BAEL-970 A Guide to Apache Commons DbUtils (eugenp#2125)
* BAEL-970 A Guide to Apache Commons DbUtils * BAEL-970 A Guide to Apache Commons DbUtils * BAEL-970 A Guide to Apache Commons DbUtils - Added employeeId to Email class - Minor corrections
1 parent 1b9353c commit 9c643cd

File tree

6 files changed

+361
-1
lines changed

6 files changed

+361
-1
lines changed

libraries/pom.xml

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,11 @@
227227
<artifactId>commons-io</artifactId>
228228
<version>${commons.io.version}</version>
229229
</dependency>
230+
<dependency>
231+
<groupId>commons-dbutils</groupId>
232+
<artifactId>commons-dbutils</artifactId>
233+
<version>${commons.dbutils.version}</version>
234+
</dependency>
230235
<dependency>
231236
<groupId>org.apache.flink</groupId>
232237
<artifactId>flink-core</artifactId>
@@ -369,7 +374,7 @@
369374
<dependency>
370375
<groupId>com.h2database</groupId>
371376
<artifactId>h2</artifactId>
372-
<version>1.4.195</version>
377+
<version>${h2.version}</version>
373378
</dependency>
374379
<dependency>
375380
<groupId>pl.pragmatists</groupId>
@@ -530,6 +535,8 @@
530535
<jetty.version>9.4.3.v20170317</jetty.version>
531536
<httpclient.version>4.5.3</httpclient.version>
532537
<commons.io.version>2.5</commons.io.version>
538+
<commons.dbutils.version>1.6</commons.dbutils.version>
539+
<h2.version>1.4.196</h2.version>
533540
<jetty.version>9.4.2.v20170220</jetty.version>
534541
<httpclient.version>4.5.3</httpclient.version>
535542
<commons.io.version>2.5</commons.io.version>
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.baeldung.commons.dbutils;
2+
3+
public class Email {
4+
private Integer id;
5+
private Integer employeeId;
6+
private String address;
7+
8+
public Integer getId() {
9+
return id;
10+
}
11+
12+
public void setId(Integer id) {
13+
this.id = id;
14+
}
15+
16+
public Integer getEmployeeId() {
17+
return employeeId;
18+
}
19+
20+
public void setEmployeeId(Integer employeeId) {
21+
this.employeeId = employeeId;
22+
}
23+
24+
25+
public String getAddress() {
26+
return address;
27+
}
28+
29+
public void setAddress(String address) {
30+
this.address = address;
31+
}
32+
33+
@Override
34+
public String toString() {
35+
return "Email{" + "id=" + id + ", address=" + address + '}';
36+
}
37+
38+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.baeldung.commons.dbutils;
2+
3+
import java.util.Date;
4+
import java.util.List;
5+
6+
public class Employee {
7+
private Integer id;
8+
private String firstName;
9+
private String lastName;
10+
private Double salary;
11+
private Date hiredDate;
12+
private List<Email> emails;
13+
14+
public Integer getId() {
15+
return id;
16+
}
17+
18+
public void setId(Integer id) {
19+
this.id = id;
20+
}
21+
22+
public String getFirstName() {
23+
return firstName;
24+
}
25+
26+
public void setFirstName(String firstName) {
27+
this.firstName = firstName;
28+
}
29+
30+
public String getLastName() {
31+
return lastName;
32+
}
33+
34+
public void setLastName(String lastName) {
35+
this.lastName = lastName;
36+
}
37+
38+
public Double getSalary() {
39+
return salary;
40+
}
41+
42+
public void setSalary(Double salary) {
43+
this.salary = salary;
44+
}
45+
46+
public Date getHiredDate() {
47+
return hiredDate;
48+
}
49+
50+
public void setHiredDate(Date hiredDate) {
51+
this.hiredDate = hiredDate;
52+
}
53+
54+
public List<Email> getEmails() {
55+
return emails;
56+
}
57+
58+
public void setEmails(List<Email> emails) {
59+
this.emails = emails;
60+
}
61+
62+
@Override
63+
public String toString() {
64+
return "Employee{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", salary=" + salary + ", hiredDate=" + hiredDate + '}';
65+
}
66+
67+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.baeldung.commons.dbutils;
2+
3+
import java.sql.Connection;
4+
import java.sql.ResultSet;
5+
import java.sql.SQLException;
6+
import java.util.HashMap;
7+
import java.util.List;
8+
import java.util.Map;
9+
import org.apache.commons.dbutils.BasicRowProcessor;
10+
import org.apache.commons.dbutils.BeanProcessor;
11+
12+
import org.apache.commons.dbutils.QueryRunner;
13+
import org.apache.commons.dbutils.handlers.BeanListHandler;
14+
15+
public class EmployeeHandler extends BeanListHandler<Employee> {
16+
17+
private Connection connection;
18+
19+
public EmployeeHandler(Connection con) {
20+
super(Employee.class, new BasicRowProcessor(new BeanProcessor(getColumnsToFieldsMap())));
21+
this.connection = con;
22+
}
23+
24+
@Override
25+
public List<Employee> handle(ResultSet rs) throws SQLException {
26+
List<Employee> employees = super.handle(rs);
27+
28+
QueryRunner runner = new QueryRunner();
29+
BeanListHandler<Email> handler = new BeanListHandler<>(Email.class);
30+
String query = "SELECT * FROM email WHERE employeeid = ?";
31+
for (Employee employee : employees) {
32+
List<Email> emails = runner.query(connection, query, handler, employee.getId());
33+
employee.setEmails(emails);
34+
}
35+
return employees;
36+
}
37+
38+
public static Map<String, String> getColumnsToFieldsMap() {
39+
Map<String, String> columnsToFieldsMap = new HashMap<>();
40+
columnsToFieldsMap.put("FIRST_NAME", "firstName");
41+
columnsToFieldsMap.put("LAST_NAME", "lastName");
42+
columnsToFieldsMap.put("HIRED_DATE", "hiredDate");
43+
return columnsToFieldsMap;
44+
}
45+
}
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
package com.baeldung.commons.dbutils;
2+
3+
import java.sql.Connection;
4+
import java.sql.DriverManager;
5+
import java.sql.SQLException;
6+
import java.util.Date;
7+
import java.util.List;
8+
import java.util.Map;
9+
import java.util.concurrent.Executors;
10+
import java.util.concurrent.Future;
11+
import java.util.concurrent.TimeUnit;
12+
import org.apache.commons.dbutils.AsyncQueryRunner;
13+
import org.apache.commons.dbutils.DbUtils;
14+
import org.apache.commons.dbutils.QueryRunner;
15+
import org.apache.commons.dbutils.handlers.BeanListHandler;
16+
import org.apache.commons.dbutils.handlers.MapListHandler;
17+
import org.apache.commons.dbutils.handlers.ScalarHandler;
18+
import org.junit.After;
19+
import static org.junit.Assert.*;
20+
import org.junit.Before;
21+
import org.junit.Test;
22+
23+
public class DbUtilsUnitTest {
24+
25+
private Connection connection;
26+
27+
@Before
28+
public void setupDB() throws Exception {
29+
Class.forName("org.h2.Driver");
30+
String db = "jdbc:h2:mem:;INIT=runscript from 'classpath:/employees.sql'";
31+
connection = DriverManager.getConnection(db);
32+
}
33+
34+
@After
35+
public void closeBD() {
36+
DbUtils.closeQuietly(connection);
37+
}
38+
39+
@Test
40+
public void givenResultHandler_whenExecutingQuery_thenExpectedList() throws SQLException {
41+
MapListHandler beanListHandler = new MapListHandler();
42+
43+
QueryRunner runner = new QueryRunner();
44+
List<Map<String, Object>> list = runner.query(connection, "SELECT * FROM employee", beanListHandler);
45+
46+
assertEquals(list.size(), 5);
47+
assertEquals(list.get(0)
48+
.get("firstname"), "John");
49+
assertEquals(list.get(4)
50+
.get("firstname"), "Christian");
51+
}
52+
53+
@Test
54+
public void givenResultHandler_whenExecutingQuery_thenEmployeeList() throws SQLException {
55+
BeanListHandler<Employee> beanListHandler = new BeanListHandler<>(Employee.class);
56+
57+
QueryRunner runner = new QueryRunner();
58+
List<Employee> employeeList = runner.query(connection, "SELECT * FROM employee", beanListHandler);
59+
60+
assertEquals(employeeList.size(), 5);
61+
assertEquals(employeeList.get(0)
62+
.getFirstName(), "John");
63+
assertEquals(employeeList.get(4)
64+
.getFirstName(), "Christian");
65+
}
66+
67+
@Test
68+
public void givenResultHandler_whenExecutingQuery_thenExpectedScalar() throws SQLException {
69+
ScalarHandler<Long> scalarHandler = new ScalarHandler<>();
70+
71+
QueryRunner runner = new QueryRunner();
72+
String query = "SELECT COUNT(*) FROM employee";
73+
long count = runner.query(connection, query, scalarHandler);
74+
75+
assertEquals(count, 5);
76+
}
77+
78+
@Test
79+
public void givenResultHandler_whenExecutingQuery_thenEmailsSetted() throws SQLException {
80+
EmployeeHandler employeeHandler = new EmployeeHandler(connection);
81+
82+
QueryRunner runner = new QueryRunner();
83+
List<Employee> employees = runner.query(connection, "SELECT * FROM employee", employeeHandler);
84+
85+
assertEquals(employees.get(0)
86+
.getEmails()
87+
.size(), 2);
88+
assertEquals(employees.get(2)
89+
.getEmails()
90+
.size(), 3);
91+
assertNotNull(employees.get(0).getEmails().get(0).getEmployeeId());
92+
}
93+
94+
@Test
95+
public void givenResultHandler_whenExecutingQuery_thenAllPropertiesSetted() throws SQLException {
96+
EmployeeHandler employeeHandler = new EmployeeHandler(connection);
97+
98+
QueryRunner runner = new QueryRunner();
99+
String query = "SELECT * FROM employee_legacy";
100+
List<Employee> employees = runner.query(connection, query, employeeHandler);
101+
102+
assertEquals((int) employees.get(0).getId(), 1);
103+
assertEquals(employees.get(0).getFirstName(), "John");
104+
}
105+
106+
@Test
107+
public void whenInserting_thenInserted() throws SQLException {
108+
QueryRunner runner = new QueryRunner();
109+
String insertSQL = "INSERT INTO employee (firstname,lastname,salary, hireddate) VALUES (?, ?, ?, ?)";
110+
111+
int numRowsInserted = runner.update(connection, insertSQL, "Leia", "Kane", 60000.60, new Date());
112+
113+
assertEquals(numRowsInserted, 1);
114+
}
115+
116+
@Test
117+
public void givenHandler_whenInserting_thenExpectedId() throws SQLException {
118+
ScalarHandler<Integer> scalarHandler = new ScalarHandler<>();
119+
120+
QueryRunner runner = new QueryRunner();
121+
String insertSQL = "INSERT INTO employee (firstname,lastname,salary, hireddate) VALUES (?, ?, ?, ?)";
122+
123+
int newId = runner.insert(connection, insertSQL, scalarHandler, "Jenny", "Medici", 60000.60, new Date());
124+
125+
assertEquals(newId, 6);
126+
}
127+
128+
@Test
129+
public void givenSalary_whenUpdating_thenUpdated() throws SQLException {
130+
double salary = 35000;
131+
132+
QueryRunner runner = new QueryRunner();
133+
String updateSQL = "UPDATE employee SET salary = salary * 1.1 WHERE salary <= ?";
134+
int numRowsUpdated = runner.update(connection, updateSQL, salary);
135+
136+
assertEquals(numRowsUpdated, 3);
137+
}
138+
139+
@Test
140+
public void whenDeletingRecord_thenDeleted() throws SQLException {
141+
QueryRunner runner = new QueryRunner();
142+
String deleteSQL = "DELETE FROM employee WHERE id = ?";
143+
int numRowsDeleted = runner.update(connection, deleteSQL, 3);
144+
145+
assertEquals(numRowsDeleted, 1);
146+
}
147+
148+
@Test
149+
public void givenAsyncRunner_whenExecutingQuery_thenExpectedList() throws Exception {
150+
AsyncQueryRunner runner = new AsyncQueryRunner(Executors.newCachedThreadPool());
151+
152+
EmployeeHandler employeeHandler = new EmployeeHandler(connection);
153+
String query = "SELECT * FROM employee";
154+
Future<List<Employee>> future = runner.query(connection, query, employeeHandler);
155+
List<Employee> employeeList = future.get(10, TimeUnit.SECONDS);
156+
157+
assertEquals(employeeList.size(), 5);
158+
}
159+
160+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
CREATE TABLE employee(
2+
id int NOT NULL PRIMARY KEY auto_increment,
3+
firstname varchar(255),
4+
lastname varchar(255),
5+
salary double,
6+
hireddate date
7+
);
8+
9+
CREATE TABLE email(
10+
id int NOT NULL PRIMARY KEY auto_increment,
11+
employeeid int,
12+
address varchar(255)
13+
);
14+
15+
CREATE TABLE employee_legacy(
16+
id int NOT NULL PRIMARY KEY auto_increment,
17+
first_name varchar(255),
18+
last_name varchar(255),
19+
salary double,
20+
hired_date date
21+
);
22+
23+
24+
INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('John', 'Doe', 10000.10, to_date('01-01-2001','dd-mm-yyyy'));
25+
INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Kevin', 'Smith', 20000.20, to_date('02-02-2002','dd-mm-yyyy'));
26+
INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Kim', 'Smith', 30000.30, to_date('03-03-2003','dd-mm-yyyy'));
27+
INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Stephen', 'Torvalds', 40000.40, to_date('04-04-2004','dd-mm-yyyy'));
28+
INSERT INTO employee (firstname,lastname,salary,hireddate) VALUES ('Christian', 'Reynolds', 50000.50, to_date('05-05-2005','dd-mm-yyyy'));
29+
30+
INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('John', 'Doe', 10000.10, to_date('01-01-2001','dd-mm-yyyy'));
31+
INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Kevin', 'Smith', 20000.20, to_date('02-02-2002','dd-mm-yyyy'));
32+
INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Kim', 'Smith', 30000.30, to_date('03-03-2003','dd-mm-yyyy'));
33+
INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Stephen', 'Torvalds', 40000.40, to_date('04-04-2004','dd-mm-yyyy'));
34+
INSERT INTO employee_legacy (first_name,last_name,salary,hired_date) VALUES ('Christian', 'Reynolds', 50000.50, to_date('05-05-2005','dd-mm-yyyy'));
35+
36+
INSERT INTO email (employeeid,address) VALUES (1, '[email protected]');
37+
INSERT INTO email (employeeid,address) VALUES (1, '[email protected]');
38+
INSERT INTO email (employeeid,address) VALUES (2, '[email protected]');
39+
INSERT INTO email (employeeid,address) VALUES (3, '[email protected]');
40+
INSERT INTO email (employeeid,address) VALUES (3, '[email protected]');
41+
INSERT INTO email (employeeid,address) VALUES (3, '[email protected]');
42+
INSERT INTO email (employeeid,address) VALUES (4, '[email protected]');
43+
INSERT INTO email (employeeid,address) VALUES (5, '[email protected]');

0 commit comments

Comments
 (0)