簡體   English   中英

MyBatis:將字符串映射到布爾值

[英]MyBatis: Map String to boolean

我在我的數據庫中插入了布爾值作為Y / N. 當我嘗試將結果映射到布爾java類型時,它總是在我的pojo中將它設置為false。

有沒有辦法將String映射到布爾值? 這是我的代碼:

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

你需要的是一個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");
    }

}

你的用法:

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

一種方法是查看實現自定義TypeHandler。 http://www.mybatis.org/mybatis-3/configuration.html#typeHandlers

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM