There is such a need :
There is a Boolean field that needs to be saved to the database, but the database does not support the Boolean type, so a single character (char (1)) is used to store the Boolean value, and a Boolean type is still used in the JavaBean.
We use MyBatis as the persistence layer framework, but there is a problem, the database is a char, and the program is a Boolean, how to implement data type automatic conversion.
Solution :
MyBatis provides support for custom type converters (Typehandler), so we can write our own type converters to implement this automatic conversion function.
implementation Steps :
The first step: writing a custom type converter
Java code /** * */ package test.atfm.persistence.mybatis.handler; import java.sql.callablestatement; import java.sql.preparedstatement; import java.sql.resultset; Import java.sql.SQLException; import org.apache.ibatis.type.jdbctype; import org.apache.ibatis.type.typehandler; /** * @author Conversion between chars in Boolean and JDBC in * java;true-y;false-n */ public class BooleanTypeHandler implements TypeHandler { /* (non-javadoc) * @see Org.apache.ibatis.type.typehandler#getresult (java.sql.resultset, java.lang.string) */ @Override &Nbsp; public object getresult (resultset arg0, string arg1 ) throws SQLException { String Str = arg0.getstring (arg1); Boolean rt = boolean.false; if ( Str.equalsignorecase ("Y") { rt = Boolean.TRUE; } return rt; } /* (non-javadoc) * @see org.apache.ibatis.type.typehandler#getresult (java.sql.callablestatement, int) */ @Override public Object GetResult (CALLABLESTATEMENT ARG0, INT ARG1) throws SQLException { boolean b = arg0.getboolean (arg1); return b == true ? "Y" : "N"; } /* (non-javadoc) * @see org.apache.ibatis.type.typehandler#setparameter (java.sql.preparedstatement, Int, java.lang.object, org.apache.ibatis.type.jdbctype) */ @Override public void setparameter ( preparedstatement arg0, int arg1, object arg2,      JDBCTYPE ARG3) throws SQLException { Boolean b = (Boolean) arg2; String value = (Boolean) b == true ? "Y" : "N"; arg0.setstring (Arg1, value); } }
Step Two: Register the type converter
XML code <?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > & lt;configuration> <properties resource= "db.properties" ></properties> <typeHandlers> <strong><span style= "color: #ff0000;" ><typehandler javatype= "Boolean" jdbctype= "CHAR" handler= "Test.atfm.persistence.mybatis.handler.BooleanTyp Ehandler "/></span></