java中跳转页面的干法_java – 有没有一种干法来整合RowMappers的相同代码?

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

public class Foo {

class AppleRows implements RowMapper {

public Apple mapRow(ResultSet rs, int rowNum) throws SQLException {

Apple a = new Apple();

a.setName(rs.getString("Name"));

}

}

class AppleRowsJoinedWithSomethingElse implements RowMapper {

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 {

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 {

public Apple mapRow(ResultSet rs, int rowNum) throws SQLException {

Apple a = new Apple();

a.setName(rs.getString("Name"));

return a;

}

}

class AppleRowsJoinedWithSomethingElse implements RowMapper {

public Apple mapRow(ResultSet rs, int rowNum) throws SQLException {

Apple a = new AppleRows().mapRow(rs, rowNum);

a.setSomethingElse(rs.getString("SomethingElse"));

return a;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值