JDBI结果集映射与连接的结果列表?

时间:2017-03-06 12:18:30

标签: java jdbc jdbi

尝试使用JDBIs ResultSetMapper API构建Country对象,但是我有一个问题,我不知道如何解决。

对于像将以下区域(州/地区)表连接到国家/地区(1 - 0..n)的结果集

enter image description here

    @Override
public Country map(final int index, final ResultSet resultRow, final StatementContext ctx) throws SQLException {

    final String countryIso3Code = resultRow.getString("iso3Code");


    return Country.builder().name(resultRow.getString("name"))
            .iso2Code(resultRow.getString("iso2Code"))
            .iso3Code(resultRow.getString("iso3Code"))
            .regions(....?)
            .build();

}

如何让ResultSetMapper使用JDBI中相应区域的相应列表初始化一个Country对象

e.g。

  

美国 - (美国) - (美国) - (PR,RI,WA)

目前返回的国家/地区列表如下所示

  

英国 - GBR - GB - <>

     

美国 - 美国 - 美国 - PR

     

美国 - 美国 - 美国 - RI

     

美国 - 美国 - 美国 - 华盛顿州

     

波多黎各 - PRI - PR - <>

     

加拿大 - CAN - CA - AB

     

加拿大 - CAN - CA - BC

1 个答案:

答案 0 :(得分:2)

您可以使用StatementContext参数。

当map方法看到一个新的国家/地区时,它会创建一个新的Country实例并调用ctx.setAttribute来保存新实例。稍后,如果存在非空区域,则将该区域添加到从语句上下文中获取的Country实例。

以下是一个例子:

    @Override
    public Country map(final int index, final ResultSet resultRow, final StatementContext ctx) throws SQLException {

        final String countryIso3Code = resultRow.getString("iso3Code");
        if (countryIso3Code == null) {
            throw new SQLDataException("Iso3Code is required");
        }
        Country country = (Country)ctx.getAttribute(countryIso3Code);
        if (country == null) {
            country = new Country();
            country.setName(resultRow.getString("name"));
            country.setIso3Code(countryIso3Code);
            country.setIso2Code(resultRow.getString("iso2Code"));
            ctx.setAttribute(countryIso3Code, country);
        }

        String region = resultRow.getString("region");
        if (region != null) {
            country.addRegion(region);
        }
        return country;
    }

使用类似于您发布的代码中的构建器有点不方便,但是可以将构建器放在语句上下文而不是国家/地区。

此外,此映射器返回每个数据库行的国家/地区,因此有七个结果,但由于重复相同的实例,因此使用Set< Country>获得预期的四个结果。

相关问题