Use jOOQ to transform java.sql.ResultSet

jOOQ has many uses. The fact that it provides a thin layer of additional abstraction over JDBC can be interesting enough for some users wanting to operate on their own java.sql.ResultSet objects. Let’s say, you prefer using JDBC directly, for query execution, rather than letting jOOQ execute queries for you:

PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();

// Instead of verbosely iterating over the above ResultSet, use jOOQ:
Factory factory = new Factory(connection, dialect);
Result<Record> result = factory.fetch(rs);

// And use jOOQ's API for more ease:
for (Record record : result) {
  System.out.print(record.getValue("ID"));
  System.out.print(": ");
  System.out.println(record.getValue("NAME"));
}

// Use jOOQ to export the result to XML or other formats:
String xml = result.formatXML();
String csv = result.formatCSV();
String json= result.formatJSON();

// Get a text version of the result for logging or console output
String text= result.format();

// Or use jOOQ to export the result into your own JPA-annotated entities
List<Value> values = result.into(Value.class);

// With Value being
public class Value {
  @Column(name = "ID")
  public Integer id;

  @Column(name = "NAME")
  public String name;
}

If you don’t want jOOQ to be your strategic SQL interface, you can still use it as a utility every now and then for your regular JDBC use.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s