Categories
Java SQL

Map JDBC result set to Java list of objects in 2 lines

In this tutorial we will see how to very simply transform a JDBC result set into a list of Java objects. Let’s say you have the following SQL table customer:

CREATE TABLE customer (name VARCHAR(50) NOT NULL, email VARCHAR(50) NOT NULL);

On the Java side, you have the following POJO called Customer:

@NoArgsConstructor
@AllArgsConstructor
@Data
class Customer {
    String name;
    String email;
}

@NoArgsConstructor, @AllArgsConstructor and @Data are annotations from the Lombok project. They add constructors, getters and setters to the POJO Customer, so that we don’t have to write all this boilerplate code. But if you prefer, you can write the getters and setters by hand.

What we want to do is select all the customers from the SQL table customers, using JDBC. We will obtain a ResultSet, and then we want to convert it into a Java List<Customer>. In order to achieve this, we can use the awesome Apache DB Utils library. Starting from a JDBC Connection object called conn, the code looks like this:

java.sql.Connection conn;

ResultSetHandler<List<Customer>> resultSetHandler = new BeanListHandler<>(Customer.class, new BasicRowProcessor(new GenerousBeanProcessor()));

String select = "select * from customer";
List<Customer> customers = new QueryRunner().query(conn, select, resultSetHandler);

We now have a List<Customer> customers with only 2 lines of code, and the code above will work the same way for more complex SQL tables / Java POJOs.

That’s it for this tutorial ! If you have any question, please leave us a reply below, we reply within 24 hours.

Leave a Reply

Your email address will not be published. Required fields are marked *