I have an application that is already using the Spring Framework and Spring JDBC with a DAO layer using the SimpleJdbcTemplate and RowMapper classes. This seems to work very well with small class structures being read from the database. However, we have the need to load objects that hold collections of other objects, which hold collections of other objects still.
The "obvious" solution to this problem is to create a named RowMapper class or our objects, and pass references to the proper DAO objects in the constructor. For example:
public class ProjectRowMapper implements ParameterizedRowMapper {
public ProjectRowMapper(AccountDAO accountDAO, ) {
this.accountDAO = accountDAO;
}
public Project mapRow(ResultSet rs, int rowNum) throws SQLException {
Project project= new Project ();
project.setProjecttId( rs.getString("project_id") );
project.setStartDate( rs.getDate("start_date") );
// project.setEtcetera(...);
// this is where the problems start
project.setAccounts( accountDAO.getAccountsOnProject(project.getProjectId()) );
}
}
The problem is that even though the ProjectDAO and the Account DAO share the same DataSource instance (in our case this is a connection pool), any database accesses are done through a different connection.
If the object hierarchy is even three levels deep, using this implementation results in (a) many calls by the framework to datasource.getConnection(), and (2) even worse, since we cap the number of connections allowed in our connection pool, potential race conditions while multiple threads are trying to load a Project from the database.
Is there a better way in Spring (without another full-fledged ORM tool) to achieve the loading of such object hierarchies?
Thanks, Paul