Search code examples
javamappingmybatisspring-mybatis

is it possible to convert values from boolean to "Y" / "N" when we save or update


I'm using mybatis with xml mappings. It so happened, that in my database I have to store boolean values in string format like : "Y"/"N". In my java code I have a lot of lines, like setValue( someBooleanValue ? "Y" : "N" ); Is there any way to store boolean values and then all these values convert to "Y" : "N" ? Maybe I can define a method or function for converting? Any ideas? Thanks


Solution

  • You need to use TypeHandlers for this.

    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.

    You can override the type handlers or create your own to deal with unsupported or non-standard types. To do so, implement the interface org.apache.ibatis.type.TypeHandler or extend the convenience class org.apache.ibatis.type.BaseTypeHandler and optionally map it to a JDBC type.

    A more complete example can be found here.