我在我的项目中使用 MyBatis 和 MySql。
我有:
myField ENUM('是','否')
我想映射到 java boolean 值:
我知道我可以修改所有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>
但是我可以用更方便的方式做到这一点吗?
最佳答案
似乎解决这个问题的最好方法是实现我自己的 boolean 类型处理程序:
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>
关于java - MyBatis Java boolean 值到 Sql 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13474296/