【问题标题】:JDBI resultset mapping with joined list of results?JDBI结果集映射与结果列表?
【发布时间】:2017-07-26 07:33:42
【问题描述】:

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

对于如下的结果集,它将地区(州/领地)表连接到国家/地区 (1 - 0..n)

    @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 对象

例如

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

目前返回的国家列表如下

英国 - GBR - GB -

美国 - 美国 - 美国 - 公关

美国 - 美国 - 美国 - RI

美国 - 美国 - 美国 - 西澳

波多黎各 - PRI - PR -

加拿大 - CAN - CA - AB

加拿大 - 加拿大 - 加利福尼亚州 - BC

【问题讨论】:

    标签: java jdbc jdbi


    【解决方案1】:

    您可以为此使用 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;
        }
    

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

    此外,此映射器为每个 DB 行返回一个国家/地区,因此有七个结果,但由于重复相同的实例,使用 Set 可以获得预期的四个结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多