jal*_*aba 5 java mybatis typehandler
我一直在尝试TypeHandler在 MyBatis 中进行自定义,以便对于null数据库中的列,MyBatis 返回Null Object 模式的实现,而不是null在域类中包含一个。
在谷歌搜索帮助后,我找到了优秀的项目mybatis-koans,即koan 19,它使用我正在使用的相同方法解决了这个问题,即扩展BaseTypeHandler<T>(是抽象的)。在这一点上,我有一个TypeHandler类似于EmailTypeHandlerkoan 的具体内容:
/**
* Acts as a factory method to return the appropriate implementation of an Email.
* Returns a Null object if the email value in the database was null/empty
*/
public class EmailTypeHandler extends BaseTypeHandler<Email> {
@Override
public Email getNullableResult(ResultSet rs, String colName) throws SQLException {
return createEmail(rs.getString(colName));
}
@Override
public Email getNullableResult(ResultSet rs, int colNum) throws SQLException {
return createEmail(rs.getString(colNum));
}
private Email createEmail(String s) {
System.out.println(s);
if (s == null || s.equals("")) {
return new NullEmail();
} else {
return new EmailImpl(s);
}
}
@Override
public Email getNullableResult(CallableStatement arg0, int arg1) throws SQLException {
return null;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int colNum,
Email e, JdbcType t) throws SQLException {
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,作者(midpeter444)似乎面临着同样的问题:当 DB 中的值为 时null,仍然返回 null 而不是在具体 中制作的对象TypeHandler。
我在发布问题后立即看到了解决方案。在BaseTypeHandler代码中:
[...]
public T getResult(ResultSet rs, String columnName) throws SQLException {
T result = getNullableResult(rs, columnName);
if (rs.wasNull()) {
return null;
} else {
return result;
}
}
public T getResult(ResultSet rs, int columnIndex) throws SQLException {
T result = getNullableResult(rs, columnIndex);
if (rs.wasNull()) {
return null;
} else {
return result;
}
}
public T getResult(CallableStatement cs, int columnIndex) throws SQLException {
T result = getNullableResult(cs, columnIndex);
if (cs.wasNull()) {
return null;
} else {
return result;
}
}
public abstract void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
public abstract T getNullableResult(ResultSet rs, String columnName) throws SQLException;
public abstract T getNullableResult(ResultSet rs, int columnIndex) throws SQLException;
public abstract T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException;
[...]
Run Code Online (Sandbox Code Playgroud)
显然,当数据库中的值为 时,BaseTypeHandler将返回,就像在这种情况下一样。因此,解决方案是创建一个具体的返回适当的实现(在本例中,当数据库中的值为 null 时为 NullObject 实现),而不进行子类化。nullnullcs.WasNull()trueTypeHandler<T>BaseTypeHandler
编辑(根据quux00的评论):当然,我们可以重写getResult的方法BaseTypeHandler,因为它的方法提供的功能setParameters可能很有用。
| 归档时间: |
|
| 查看次数: |
5065 次 |
| 最近记录: |