I am using JDBC (and spring-jdbc’s jdbcTemplate) to access my database in a java web application. I have many different varying queries, some where I join to the table over there, one with the subquery that, one using a group by here etc. etc.
Oftentimes I need the result just to display a particular table that is generated by JSP, so I can just use the convenient queryForList method that returns a List<Map<String, Object>>, a List with each row represented by a map that maps column names to values. In JSP this is just fine, there is no compile time type check anyway, no code completion for properties by eclipse etc.
But sometimes I have java code to process the query result and I think it would be helpful to not work with maps, but with real objects, mainly for having a compile time check whether to properties really exist, have the correct type and of course to have code completion.
But if I want that I need to write an Object for every single query which may be many objects (pages of code with nothing but setters and getters).
What would be the best way to deal with that situation? Just write those darn objects? Or is there a better way?
You want the compiler to understand your object model, so (in Java, at least) you will need to create it, I’m afraid.
A decent IDE will provide options to generate get/set methods for you from members variables, which can be a timesaver. If the object model exists purely to apply some semantics over the JDBC queries and not business logic, perhaps public members are appropriate, avoiding the need for the getters and setters in the style of the J2EE Transfer Object pattern. Just watch out for business logic creeping in there, and don’t forget about equals() and hashCode().
There is some help available for doing the mapping to and from your objects though, in Spring JDBC, like RowMapper and MappingSqlQuery. You may also want to check out Object Relational Mapping frameworks like Spring ORM to save yourself some effort. I think these approaches save time in writing translation code to and from SQL, managing transactions and the database schema – we still need to create the object model.