MyBatis Java 布尔类型转换为 SQL 枚举

3
我将使用MyBatis和MySql在我的项目中。
我有一个myField ENUM('yes','no'),我想将其映射到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>

但是我能以更便捷的方式完成吗?
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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接