java – 有没有一种干法来整合RowMappers的相同代码?

我正在使用JDBC,我的许多类都有一个内部RowMapper类,如下所示:

public class Foo {
  class AppleRows implements RowMapper<Apple> {
    public Apple mapRow(ResultSet rs, int rowNum) throws SQLException {
      Apple a = new Apple();
      a.setName(rs.getString("Name"));
    }
  }

  class AppleRowsJoinedWithSomethingElse implements RowMapper<Apple> {
    public Apple mapRow(ResultSet rs, int rowNum) throws SQLException {
      Apple a = new Apple();   
      a.setName(rs.getString("Name"));
      a.setSomethingElse(rs.getString("SomethingElse"));
    } 
  }
}

在上面的示例中,行a.setName(rs.getString(“Name”))正在被复制.这只是一个例子,但在我的实际代码中有超过10个这样的字段.我想知道是否有更好的方法来做到这一点?

注意:我需要不同的映射器,因为我在一些地方使用它们,我正在将结果与另一个表(获取更多字段)联系起来.

最佳答案 你可以扩展使用super.mapRow()…

public class Foo {
  class AppleRows implements RowMapper<Apple> {
    public Apple mapRow(ResultSet rs, int rowNum) throws SQLException {
      Apple a = new Apple();
      a.setName(rs.getString("Name"));
      return a;
    }
  }

  class AppleRowsJoinedWithSomethingElse extends AppleRows {
    public Apple mapRow(ResultSet rs, int rowNum) throws SQLException {
      Apple a = super.mapRow(rs, rowNum);
      a.setSomethingElse(rs.getString("SomethingElse"));
      return a;
    } 
  }
}

或者只是委托,如果你不喜欢使用继承作为代码重用的机制:

public class Foo {
  class AppleRows implements RowMapper<Apple> {
    public Apple mapRow(ResultSet rs, int rowNum) throws SQLException {
      Apple a = new Apple();
      a.setName(rs.getString("Name"));
      return a;
    }
  }

  class AppleRowsJoinedWithSomethingElse implements RowMapper<Apple> {
    public Apple mapRow(ResultSet rs, int rowNum) throws SQLException {
      Apple a = new AppleRows().mapRow(rs, rowNum);
      a.setSomethingElse(rs.getString("SomethingElse"));
      return a;
    } 
  }
}
点赞