So far the way I make simple POJOs from database queries is as follows:
CallableStatementCallback<Integer> csc = new CallableStatementCallback<Integer>() {
@Override
public Integer doInCallableStatement(CallableStatement cs)
throws SQLException, DataAccessException {
cs.execute();
ResultSet rs = cs.getResultSet();
if (rs != null && rs.next()) {
SomePojoClass spc = new SomePojoClass();
spc.setFirstValue(rs.getLong("first")); //column names from table
spc.setSecondValue(rs.getString("second"));
spc.setThirdValue(rs.getString("third"));
spcList.add(spc);
return 1;
}
return 0;
}
};
Obviously this maps each row to a new POJO. But I have a SQL query that returns rows like this:
[parent row 1] - [child row 1] (returned as one row obviously)
[parent row 1] - [child row 2]
[parent row 2] - [child row 1]
[parent row 2] - [child row 2]
[parent row 2] - [child row 3]
[parent row 3] - [child row 1]
etc. This is pretty common way of getting a SQL result set because of one to many relations... and doing redundant queries for a fairly simple structure seems unnecessary (and potentially inefficient). Is there an established easy way of parsing this into java objects? i.e. instead of iterating over a ResultSet class and creating and setting a new object for each row, I want to iterate over the set and create a new object for each parent row and a new object for each child row.
For example one idea could be to order the query by parent primary key, then generate a new parent-object only when the parent id changed, but still make a new child-object for each row, and tie the parents and children together whenever the parent id of the next row would change. But I don't know if this is the right way to do it.