我使用JDBC和我的許多類都有一個內部的RowMapper類如下:是否有乾淨的方式來整合RowMappers的相同代碼?
在上面的例子線a.setName(rs.getString("Name"))
被複制。這只是一個例子,但在我的實際代碼中有超過10個這樣的字段。我想知道是否有更好的方法來做到這一點?
注意:我需要不同的映射器,因爲我在一些地方使用它們,我用另一個表格來獲取結果(獲取更多的字段)。
我使用JDBC和我的許多類都有一個內部的RowMapper類如下:是否有乾淨的方式來整合RowMappers的相同代碼?
在上面的例子線a.setName(rs.getString("Name"))
被複制。這只是一個例子,但在我的實際代碼中有超過10個這樣的字段。我想知道是否有更好的方法來做到這一點?
注意:我需要不同的映射器,因爲我在一些地方使用它們,我用另一個表格來獲取結果(獲取更多的字段)。
你可以extend
+使用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;
}
}
}
的一種可行方式這樣做會使用繼承,特別是如果你可以使內部類成爲static
嵌套類,如下所示:
public class Foo {
static 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;
}
}
static 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;
}
}
}
我在這裏使用static
嵌套類的原因是因爲在未使用(至少在當前實現中)的非static
嵌套類中存在對包含類的實例的隱式引用。
每個映射器映射單個行定義。我不會稱這違反DRY。
如果AppleRowsJoinedWithSomethingElse
的底層視圖中的單個列名更改,則只需在一個位置更改它。
如果您使用通用代碼重構此代碼,那麼如果提供AppleRowsJoinedWithSomethingElse
的視圖發生更改,您將處於一個奇怪的位置,但AppleRows
不支持該視圖。
不需要擴展以共享通用功能。我只是輸入這個,所以它可能不會真正編譯。
public class CommonBlammy
{
private CommonBlammy() { } // private constructor to prevent instantiation.
public static Apple mapRow(final ResultSet resultSet)
throws SQLException
{
Apple returnValue = new Apple();
returnValue.setName(resultSet.getString("Name"));
return returnValue;
}
}
public class AppleRows implements RowMapper
{
public Apple mapRow(
final ResultSet resultSet,
final int rowNumber)
throws SQLException
{
return CommonBlammy.mapRow(ResultSet resultSet);
}
}
public class AppleRowsJoinedWithSomethingElse implements RowMapper
{
public Apple mapRow(
final ResultSet resultSet,
final int rowNumber)
throws SQLException
{
Apple returnValue;
returnValue = CommonBlammy.mapRow(ResultSet resultSet);
returnValue.setSomethingElse(rs.getString("SomethingElse"));
return returnValue;
}
}