Let's say I have an object with two different one-to-many relations. Much like:
Customer 1<->M Brands
and Customer 1<->M Orders
And let's say that the my object Customer
has two lists related to those two objects.
I've read this example:
http://forum.springsource.org/showthread.php?50617-rowmapper-with-one-to-many-query
which explains how to do it with a single one-to-many relationship. For your convenience here's the ResultSetExtractor
override:
private class MyObjectExtractor implements ResultSetExtractor{
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
Map<Integer, MyObject> map = new HashMap<Integer, MyObject>();
MyObject myObject = null;
while (rs.next()) {
Integer id = rs.getInt("ID);
myObject = map.get(id);
if(myObject == null){
String description = rs,getString("Description");
myObject = new MyObject(id, description);
map.put(id, myObject);
}
MyFoo foo = new MyFoo(rs.getString("Foo"), rs.getString("Bar"));
myObject.add(myFoo);
}
return new ArrayList<MyObject>(map.values());;
}
}
I don't think it covers how to work with both. What would be the cleanest approach? Is there a simpler way than to iterate with conditions? Would sets be better off than lists in this case?
See Question&Answers more detail:os