Java Reference
In-Depth Information
public interface RowMapper<T> {
T mapRow(ResultSet rs, int rowNum) throws SQLException
}
Whenyouexecute oneofthe
query
methods in
JdbcTemplate
,Springtakes the
Res-
ultSet
and feeds each row through an implementation of the
RowMapper
interface.
The job of the
mapRow
method is then to convert that row into an instance of the domain
class. The normal Java implementation would be to create an inner class called, say,
Ac-
countMapper
, whose
mapRow
method would extract the data from the
ResultSet
row and convert it into an
Account
instance. Providing an instance of the
Accoun-
tMapper
class to the
queryForObject
method would then return a single
Account
.
The same instance can be supplied to the
query
method, which then returns a collection
of
Account
s.
accountMapper
is defined and assigned to a closure with the same arguments as the re-
quired
mapRow
method. The variable is then used in both the
findAccountById
and
findAllAccounts
methods.
There are two uses for Groovy here:
1
. A Groovy class implemented a Java interface, which makes integration easy and
simplifies the code.
2
. Closure coercion eliminated the expected inner class.
Inthe example in the booksource code Ialso included the service class referenced in
figure
a required transaction. There is nothing inherently Groovy about it, so again I'll just show
an outline of the implementation in the next listing.