如何将结果集映射到嵌套的对象结构?

时间:2013-06-17 13:22:52

标签: java sqlresultsetmapping

我有这样的结果集......

+--------------+--------------+----------+--------+
| LocationCode | MaterialCode | ItemCode | Vendor |
+--------------+--------------+----------+--------+
|            1 |           11 |      111 |   1111 |
|            1 |           11 |      111 |   1112 |
|            1 |           11 |      112 |   1121 |
|            1 |           12 |      121 |   1211 |
+--------------+--------------+----------+--------+

对于LocationCode 2,3,4等等我需要一个对象(最终转换为json):List<Location> 位置类中嵌套对象的层次结构是..

Location.class
    LocationCode
    List<Material>

Material.class
    MaterialCode
    List<Item>

Item.class
    ItemCode
    Vendor

这对应于结果集,其中1个位置有2个材料,1个材料(11)有2个项目,1个项目(111)有2个供应商。

我如何实现这一目标?我之前使用过AliasToBeanResultTransformer,但我怀疑在这种情况下它会有所帮助。

1 个答案:

答案 0 :(得分:1)

我认为没有一种巧妙的方法来进行映射。我只是用嵌套循环和自定义逻辑来决定何时开始构建下一个Location,Material,Item等等。

像这样的伪代码:

while (row = resultSet.next()) {
    if (row.locationCode != currentLocation.locationCode) {
        currentLocation = new Location(row.locationCode)
        list.add(currentLocation)
        currentMaterial = null
    } else if (currentMaterial == null ||
               row.materialCode != currentMaterial.materialCode) {
        currentMaterial = new Material(row.materialCode)
        currentLocation.add(currentMaterial)
    } else {
        currentMaterial.add(new Item(row.itemCode, row.vendorCode))
    }
}
相关问题