MyBatis:将字符串映射到布尔值

时间:2017-01-05 13:01:53

标签: java mybatis

我在我的数据库中插入了布尔值作为Y / N.当我尝试将结果映射到布尔java类型时,它总是在我的pojo中将它设置为false。

有没有办法将String映射到布尔值?这是我的代码:

<resultMap id="getFlag" type="MyPojo">
    <result property="myFlag" column="MY_FLAG"/>
</resultMap>

2 个答案:

答案 0 :(得分:8)

你需要的是一个typeHandler为你Y / N布尔类型: (more explained here) 实际处理程序:

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");
    }

}

您的用法:

<result property="myFlag" column="MY_FLAG" javaType="java.lang.Boolean" jdbcType="VARCHAR" typeHandler="com.foo.bar.YesNoBooleanTypeHandler" />

答案 1 :(得分:1)

一种方法是查看实现自定义TypeHandler。 http://www.mybatis.org/mybatis-3/configuration.html#typeHandlers