Extending database access
zero.data to access your data.
The default behavior and convenience methods of zero.data meets most needs.
However, a major goal of zero.data is that the underlying engine provides a
pluggable infrastructure. This means that you can provide implementations of
known interfaces to introduce custom functionality. For instance, if an
application needs to introduce new content types in its RESTful API that
exposes relational data, this can be accomplished by creating a RowHandler
or ResultHandler.
Contents
RowHandler - returning custom data structures
When convenience methods don't work and you need to customize the data structure
that is returned, you can roll your own RowHandler. This interface
defines the handle method that takes a ResultSet and a parameterized type
T. It maps data in a single row to a class. In fact, all of the query
convenience methods described in this documentation use out of the box
implementations of RowHandler function. For instance, MapRowHandler and
BeanRowHandler are such implementations.
To use RowHandler, first define an implementation. If you plan to reuse the
implementation, implement it normally as a public class. If it is a one off
implementation, you can define it anonymously. The following example shows
RowHandler being implemented as an anonymous class:
public class CustomClass {
public String customProp1;
public Date customProp2;
}
import java.sql.ResultSet;
import com.ibm.pdq.runtime.handlers.RowHandler;
...
CustomClass myCustCls = data.queryFirst( "SELECT column1,column2 FROM sometable WHERE id=?", new RowHandler() {
public CustomClass handle(ResultSet resultSet, CustomClass obj) {
CustomClass custom = new CustomClass();
custom.customProp1 = resultSet.getString(1);
custom.customProp2 = resultSet.getDate(2);
return custom;
}
}, 100 /* don't forget the parameters! */);
System.out.print(myCustCls.toString()); // do something interesting with myCustCls
Using ResultHandler to handle the entire ResultSet
Using the ResultHandler is especially useful in translating ResultSet
directly into customized Java classes. Many other frameworks would require
mapping the ResultSet to a Java bean and then mapping the bean to another
class or data structure. Using the pluggable ResultHandler you can
completely customize the data access functionality. The previous example showed
how implementing a custom RowHandler can change how Manager processes
individual ResultSet rows. If, however, more fine grained control over
ResultSet handling is required, implement ResultHandler. Like
RowHandler, this can be a one off as an anonymous class or a reused pattern
as its own class. ResultHandler is responsible for looping over the
ResultSet and producing something useful. It might or might not use a
RowHandler. In fact, depending on needs, it can use more than one
RowHandler.