Object relational mappers allow you to map a lower level sql query to a java object. While spring's JdbcTemplate isn't considered a ORM, lets find out how to map a sql result set to a domain object.
Detailed Video Notes
JdbcTemplate is a core class within spring-jdbc that simplifies making data access calls that handles resource management such as closing and creating connections. It is a lighter weight alternative to mybatis or ibatis and hibernate especially if you are already working within spring context. Since it is easier to manage a list of business objects vs lower level resultset, lets find out how to map a jdbc row to a domain object.
In order to map a jdbc resultset we will need to create a State object with attributes of stateId as a primary key, abbreviation of the state, postalCode and a field for state itself. Overriding the object toString will give pretty output in our console.
The class that does the heavy lifting is StateRowMapper which implements spring's RowMapper. It's primary responsibility is to map each row of the result set object to the State POJO object. Since we know that we will reuse it in a couple of our examples we create an inner class but could of been substituted with an anonymous inner class when calling jdbcTemplate.
To map a single result row to our java object State we will call jdbcTemplate.queryForObject passing in the sql to execute and the StateRowMapper. Running the junit test the output shows that the sql is executed and the State was logged.
To map a list of records is very similar. Instead of calling jdbcTemplate.queryForObject using jdbcTemplate.query will execute a state query that will return all states in our table, then it will map each row to a State java object via a StateRowMapper. Again, running our unit test will show that the size of the states list is three.
While this tutorial shows the basics of mapping rows of a ResultSet to java object there is much, much more.
Thanks for joining in today's level up, have a great day!