For a new project, we’ve decided to use Spring MVC, and JdbcTemplate (specifically SimpleJdbcTemplate) for persisting domain objects. One issue I’ve been having with this approach is how to cleanly create object graphs from SELECT queries. The RowMapper mechanism seems to work great when I am pulling rows from a single table; I become concerned when I’m mapping the results of a JOIN query.
To give a concrete (yet entirely fabricated) example, suppose I have two entities in an N-to-1 relationship:
public class Invoice {
private Customer customer;
...
}
public class Customer {
private int id;
private String name;
...
}
I would like to be able to call a selectInvoices() method on my InvoiceDAO, and retrieve a list of Invoice‘s populated with fully-formed Customer instances. Instead, I find myself tempted to do something like the following:
public class Invoice {
// this makes me unhappy
private int customerId;
...
}
What is the best practice for cleanly making this happen? Should I just bite the bullet and use an ORM?
This is exactly what an ORM is good at. If you want to do it all by yourself, my trick is to use a map to hold the customers: