views:

303

answers:

1

I wanted to know what the community considers the "best practices" in respect to mapping class hierarchies with Spring JDBC.

We do not have the ability to use a full fledged ORM tool, however we are using the Spring JDBC to alleviate some of the tedious nature of JDBC. One class which we leverage very regularly are the BeanPropertyRowMapper for it's ease of use and the ability to have type insensitive bean property access from our result set.

I have a class hierarchy that all maps back to a single table (taking the table-per-hiearchy approach for this small class hierarchy). As such, the table contains an classId column which can be used to determine what class should actually be instantiated. Ex. 1 = Manager, 2 = Employee, 3 = Contractor. All of these are "People" but each subclass of person has a few attributes which are unique to their class.

My initial thought is to create a subclass of BeanPropertyRowMapper and try and inject this logic to say "if column A = 1 then instantiate a Manager and then do your nomral binding".

Does this seem like a reasonable approach? Are there any other suggestions people may have that have worked for you?

Thanks in advance for your replies,

Justin N.

+2  A: 

It doesn't look like there's a place in the subclass where you could add a hook to switch the class without completely copying the implementation of mapRow() for BeanPropertyRowMapper. Your best approach might be to create a RowMapper class that delegates to the appropriate BeanPropertyRowMapper.

For example:

    final RowMapper managerMapper = new BeanPropertyRowMapper(Manager.class);
    final RowMapper employeeMapper = new BeanPropertyRowMapper(Employee.class);
    final RowMapper contractorMapper = new BeanPropertyRowMapper(Contractor.class);

    RowMapper rm = new RowMapper()
    {
        @Override
        public Object mapRow(ResultSet rs, int rowNum)
            throws SQLException
        {
            int employeeType = rs.getInt("type");
            switch (employeeType)
            {
                case 1:
                    return managerMapper.mapRow(rs, rowNum); 

                case 2:
                    return employeeMapper.mapRow(rs, rowNum);

                case 3:
                    return contractorMapper.mapRow(rs, rowNum);

                default:
                    break;

            }
        }
    };
Jason Gritman
Thanks for the response. This is what I had ended up doing! Good to get some validation.
jnt30