本文介绍了在MyBatis的where子句中使用类型处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在MyBatis中编写动态查询时,可以在where子句中使用类型处理程序吗?
Can I use type handler in where clause when writing dynamic query in MyBatis?
我必须将布尔值转换为char.假将转换为"N",真将转换为"Y".由于该列中的值存储为Y或N
I have to convert the Boolean value to char. the false will be converted to "N" and true to "Y". As the value store in the column are either Y or N
推荐答案
是的,您可以使用MyBatis类型处理程序
Yes , you can use MyBatis typehandlers
public class YesNoBooleanTypeHandler extends BaseTypeHandler<Boolean> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType)
throws SQLException {
ps.setString(i, convert(parameter));
}
@Override
public Boolean getNullableResult(ResultSet rs, String columnName)
throws SQLException {
return convert(rs.getString(columnName));
}
@Override
public Boolean getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
return convert(rs.getString(columnIndex));
}
@Override
public Boolean getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return convert(cs.getString(columnIndex));
}
private String convert(Boolean b) {
return b ? "Y" : "N";
}
private Boolean convert(String s) {
return s.equals("Y");
}
}
Mapper.xml where子句:
Mapper.xml where clause:
... WHERE your_bool = #{yourBool,typeHandler=YesNoBooleanTypeHandler} ...
这篇关于在MyBatis的where子句中使用类型处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!