[英]MyBatis: Map String to boolean
I have booleans inserted in my database as Y/N. 我在我的数据库中插入了布尔值作为Y / N. When I try to map the result to a boolean java type, it always set it to a false in any case in my pojo.
当我尝试将结果映射到布尔java类型时,它总是在我的pojo中将它设置为false。
Is there any way to map String to boolean? 有没有办法将String映射到布尔值? Here's my code:
这是我的代码:
<resultMap id="getFlag" type="MyPojo">
<result property="myFlag" column="MY_FLAG"/>
</resultMap>
What you need is a typeHandler for you Y/N Boolean type: ( more explained here ) Actual Handler: 你需要的是一个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");
}
}
Your usage: 你的用法:
<result property="myFlag" column="MY_FLAG" javaType="java.lang.Boolean" jdbcType="VARCHAR" typeHandler="com.foo.bar.YesNoBooleanTypeHandler" />
One way to do it would be to look at implementing a custom TypeHandler. 一种方法是查看实现自定义TypeHandler。 http://www.mybatis.org/mybatis-3/configuration.html#typeHandlers .
http://www.mybatis.org/mybatis-3/configuration.html#typeHandlers 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.