Java Reference
In-Depth Information
One possible solution is to transform the map into a new one with lowercase keys. That's
what the collectEntries method in the Map class is for. The resulting implementa-
tion of the findProductById method is therefore
Product findProductById(int id) {
def row = sql.firstRow('select * from product where id=?', id)
new Product( row.collectEntries { k,v -> [k.toLowerCase(), v] } );
}
It would be easy enough to generalize this to the getAllProducts method by using
eachRow and transforming them one at a time. A somewhat more elegant solution is to
use the rows method and transform the resulting list of maps directly:
List<Product> getAllProducts() {
sql.rows('select * from product').collect { row ->
new Product(
row.collectEntries { k,v -> [k.toLowerCase(), v] }
)
}
}
This solution is either incredibly elegant or too clever by half, depending on your point of
view. Collecting [ 2 ] everything together (except for the initialization shown in the construct-
or already), the result is shown in the following listing.
2 No pun intended.
Listing 8.7. The complete SqlProductDAO class, except for the parts already shown
class SqlProductDAO implements ProductDAO {
Sql sql = Sql.newInstance(url:'jdbc:h2:mem:',driver:'org.h2.Driver')
List<Product> getAllProducts() {
sql.rows('select * from product').collect { row ->
new Product(
row.collectEntries { k,v -> [k.toLowerCase(), v] }
)
}
}
Product findProductById(int id) {
def row = sql.firstRow('select * from product where id=?', id)
new Product(
row.collectEntries { k,v -> [k.toLowerCase(), v] } );
}
 
Search WWH ::




Custom Search