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

Jul*_*nez 6 java mybatis

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

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

<resultMap id="getFlag" type="MyPojo">
    <result property="myFlag" column="MY_FLAG"/>
</resultMap>
Run Code Online (Sandbox Code Playgroud)

hak*_*iri 8

你需要的是一个typeHandler为你Y/N布尔类型:( 更多解释这里)实际处理程序:

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

}
Run Code Online (Sandbox Code Playgroud)

你的用法:

<result property="myFlag" column="MY_FLAG" javaType="java.lang.Boolean" jdbcType="VARCHAR" typeHandler="com.foo.bar.YesNoBooleanTypeHandler" />
Run Code Online (Sandbox Code Playgroud)

  • 记住在创建SqlSessionFactoryBean时注册您的Y/N TypeHandler,如下所示:factory.setTypeAliases(new Class [] {YesNoBooleanTypeHandler.class}).您必须已在applicationContext.xml [如果使用Spring XML]或Spring Config @Configuration [如果使用java注释]中配置SqlSesionFactory. (2认同)