Reputation: 57
Can I use type handler in where clause when writing dynamic query in MyBatis?
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
Upvotes: 0
Views: 3633
Reputation: 4169
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 clause:
... WHERE your_bool = #{yourBool,typeHandler=YesNoBooleanTypeHandler} ...
Upvotes: 3