3

我在我的项目中使用 MyBatis 和 MySql。

我有:

myField 枚举('是','否')

我想映射到java布尔值:

我知道我可以修改所有 mybatis 模板,例如:

<update id="update">
UPDATE
myTable
   <set>
        ...
       <if test="myField != null">myField = <choose>
           <when test="myField == true">'yes'</when>
           <otherwise>'no'</otherwise>
           </choose>,
        </if>
        ...
    </set>
 WHERE
    ...
 </update>

但是我能以更方便的方式做到这一点吗?

4

1 回答 1

11

似乎解决这个问题的最好方法是实现我自己的布尔类型处理程序:

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 ? "yes" : "no";
    }

    private Boolean convert(String s) {
        return s.equals("yes");
    }

}

然后在映射器模板中使用它:

<update id="update">
UPDATE
myTable
   <set>
        ...
       <if test="myField != null">myField = #{myField ,typeHandler=YesNoBooleanTypeHandler}</if>
        ...
    </set>
 WHERE
    ...
 </update>
于 2012-11-21T07:00:21.047 回答