 |
JDBC Without Code Repetition
Many examples of JDBC programming seem to fall short by using many repeated code structures. Examples of repeated items might include
- fetching a connection
- iterating over a ResultSet
- closing statements and connections
- handling SQLException
- manipulating raw SQL text
- inserting parameters into SQL statements
- logging of warnings
Here, the DontRepeatYourself principle seems very useful. If repeated code structures are aggressively removed, JDBC code can become surprisingly compact. This significantly increases the attractiveness of JDBC as a general persistence mechanism.
Here is an an example of an application whose data layer does not repeat JDBC code:
In particular note these data layer items, which form a small layer of abstraction over the most commonly used parts of the JDBC API:
The various XXXDAOSql classes in the data layer are users of the above items. Their implemenations are quite compact.
Also to note :
- the above javadoc was built with the -linksource option, and all underlying source code is available through links under class and method names.
- distributed transactions can wrap multiple connections in a single transaction, whereas regular JDBC transactions are attached to a single connection. The above scheme fetches a new connection for each interaction with the database. Hence, the above scheme will work with distributed transactions, but falls short if "old style" JDBC transactions are used. This is a definite drawback, but distributed transactions are probably the recommended style.
See also
Discussion
|