MyBatis Java布尔值转换为Sql枚举 [英] MyBatis Java Boolean to Sql enum
本文介绍了MyBatis Java布尔值转换为Sql枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的项目中使用MyBatis和MySql.
I am using MyBatis with MySql in my project.
我有:
myField ENUM('yes','no')
myField ENUM('yes','no')
我想映射到Java布尔值:
and I want to map in to java boolean value:
我知道我可以修改所有mybatis模板,例如:
I know I can modify all mybatis templates, e.g.:
<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>
但是我能以更方便的方式做到这一点吗?
But can I do this in more convenient way?
推荐答案
似乎解决此问题的最佳方法是实现我自己的布尔类型处理程序:
It seems the best way to solve this is to implement my own boolean type handler:
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");
}
}
,然后在映射器模板中使用它:
and then to use it in the mapper template:
<update id="update">
UPDATE
myTable
<set>
...
<if test="myField != null">myField = #{myField ,typeHandler=YesNoBooleanTypeHandler}</if>
...
</set>
WHERE
...
</update>
这篇关于MyBatis Java布尔值转换为Sql枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文