带有类Hiearchies的Spring JDBC RowMapper

jnt*_*t30 5 java orm spring spring-jdbc class-hierarchy

我想知道社区认为使用Spring JDBC映射类层次结构的"最佳实践".

我们没有能力使用完整的ORM工具,但我们使用Spring JDBC来缓解JDBC的一些乏味特性.我们非常经常使用的一个类是BeanPropertyRowMapper,因为它易于使用,并且能够从我们的结果集中访问类型不敏感的bean属性.

我有一个类层次结构,它都映射回一个表(对于这个小类层次结构采用table-per-hiearchy方法).因此,该表包含一个classId列,可用于确定实际应该实例化哪个类.防爆.1 =经理,2 =员工,3 =承包商.所有这些都是"人",但每个人的子类都有一些属性,这些属性对于他们的类是唯一的.

我最初的想法是创建一个BeanPropertyRowMapper的子类,并尝试注入这个逻辑,说"如果列A = 1然后实例化一个管理器,然后进行你的标题绑定".

这看起来像是一种合理的方法吗?人们可能有任何其他建议吗?

提前感谢您的回复,

贾斯汀N.

Jas*_*man 4

子类中似乎没有一个地方可以添加钩子来切换类,而无需完全复制 BeanPropertyRowMapper 的 mapRow() 实现。您的最佳方法可能是创建一个委托给适当的 BeanPropertyRowMapper 的 RowMapper 类。

例如:

    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;

            }
        }
    };
Run Code Online (Sandbox Code Playgroud)