I have booleans inserted in my database as 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.
Is there any way to map String to boolean? Here's my code:
<resultMap id="getFlag" type="MyPojo">
<result property="myFlag" column="MY_FLAG"/>
</resultMap>
The resultMap element is the most important and powerful element in MyBatis. It's what allows you to do away with 90% of the code that JDBC requires to retrieve data from ResultSet s, and in some cases allows you to do things that JDBC does not even support.
typeHandlers. Whenever MyBatis sets a parameter on a PreparedStatement or retrieves a value from a ResultSet, a TypeHandler is used to retrieve the value in a means appropriate to the Java type.
What you need is a typeHandler for you Y/N Boolean type: (more explained here) Actual 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 ? "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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With