MyBatis:将字符串映射到布尔值
MyBatis: Map String to boolean
我在我的数据库中插入了布尔值 Y/N。当我尝试将结果映射到布尔 java 类型时,它总是在我的 pojo 中将其设置为 false。
有没有办法将字符串映射为布尔值?这是我的代码:
<resultMap id="getFlag" type="MyPojo">
<result property="myFlag" column="MY_FLAG"/>
</resultMap>
一种方法是查看实现自定义 TypeHandler。
http://www.mybatis.org/mybatis-3/configuration.html#typeHandlers.
你需要的是一个适合你的typeHandlerY/N布尔类型:
(more explained here)
实际处理人:
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");
}
}
您的使用情况:
<result property="myFlag" column="MY_FLAG" javaType="java.lang.Boolean" jdbcType="VARCHAR" typeHandler="com.foo.bar.YesNoBooleanTypeHandler" />
我在我的数据库中插入了布尔值 Y/N。当我尝试将结果映射到布尔 java 类型时,它总是在我的 pojo 中将其设置为 false。
有没有办法将字符串映射为布尔值?这是我的代码:
<resultMap id="getFlag" type="MyPojo">
<result property="myFlag" column="MY_FLAG"/>
</resultMap>
一种方法是查看实现自定义 TypeHandler。 http://www.mybatis.org/mybatis-3/configuration.html#typeHandlers.
你需要的是一个适合你的typeHandlerY/N布尔类型: (more explained here) 实际处理人:
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");
}
}
您的使用情况:
<result property="myFlag" column="MY_FLAG" javaType="java.lang.Boolean" jdbcType="VARCHAR" typeHandler="com.foo.bar.YesNoBooleanTypeHandler" />