0

在 MyBatis 中编写动态查询时,我可以在 where 子句中使用类型处理程序吗?

我必须将布尔值转换为字符。false 将转换为“N”,true 将转换为“Y”。由于列中存储的值是 Y 或 N

4

1 回答 1

2

是的,你可以使用 MyBatis 类型处理程序

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 子句:

... WHERE your_bool = #{yourBool,typeHandler=YesNoBooleanTypeHandler} ...
于 2013-06-27T14:15:31.607 回答