【问题标题】:MyBatis: Map String to booleanMyBatis:将字符串映射为布尔值
【发布时间】:2017-01-05 13:01:52
【问题描述】:

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

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

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

【问题讨论】:

标签: java mybatis


【解决方案1】:

你需要的是一个 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" />

【讨论】:

  • 记住在创建 SqlSessionFactoryBean 时注册 Y/N TypeHandler,如下所示:factory.setTypeAliases(new Class[]{YesNoBooleanTypeHandler.class})。您必须已经在 applicationContext.xml [如果使用 Spring XML] 或 Spring Config @Configuration [如果使用 java 注释] 中配置了 SqlSessionFactory。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2019-06-09
    • 2019-07-03
    • 2014-11-27
    • 1970-01-01
    • 2017-07-31
    • 2017-08-04
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多