Thursday, April 22, 2010

ActiveJDBC the Basics

The title of this post has a class name in it...almost. The real class name is activejdbc.Base

This is an interesting class, in a sense that it is a completely static class (all methods static) and it is designed to wrap standard JDBC functionality in the most simple and succinct way humanly possible.
It allows to open a connection, query DB and close a connection in 3 lines of code - you have to write a half of page for this in any Java technology!
Here are some examples:"oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:@localhost:1521:xe", "usr", "pwd1");
List<Map> records = Base.findAll("select * from people");
//..iterate over list
As you can see, this exposes all SQL that is interesting to a developer and hides all the ungodliness of JDBC, including driver, connection, exceptions, etc.
I literally bent backwards (well almost:)) to make this code as clear as possible.
In the example above, the opens a connection and attaches it to a thread. This allows any subsequent call consume it, while Base.close() closes the connection, obviously.
Another example:
List<Map> records = Base.findAll("select * from people where last_name = ? and name = ?", "Smith", "John");
I think this one is self-explanatory...and another one:
Base.find("select * from people", new RowListenerAdapter() {
            public void onNext(Map record) {
In the former examples, the entire result set (findAll()) was read into a list, but in some cases you will need to read millions of records and process them as in the stream (SAX - style of sorts).
The latter example achieves this goal, and you do not have to write a loop, the Base class takes care of it.

The Base class is not a super class to anything. It is just a utility that can be used externally and of course is used internally by the framework.