需求场景:当数据库中保存'Y'/'N',而对应bean字段的值的类型为boolean,这是就需要我们自定义类型转换器,在Mybatis执行SQL得到结果时,通过自定义类型转换器将CHAR或者VARCHAR2类型转换为boolean类型,Java代码如下:
- package com.mangocity.btms.dynamicfield.util;
-
- import org.apache.ibatis.type.JdbcType;
- import org.apache.ibatis.type.TypeHandler;
- import org.apache.log4j.Logger;
-
- import java.sql.CallableStatement;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
-
-
-
-
-
- public class mangoBooleanTypeHandler implements TypeHandler<Boolean> {
- private static final Logger logger = Logger.getLogger(mangoBooleanTypeHandler.class) ;
-
-
-
-
-
-
-
-
-
- public void setParameter(PreparedStatement preparedStatement, int i, Boolean b, JdbcType jdbcType) throws SQLException {
- if(b.equals(Boolean.TRUE)){
- preparedStatement.setString(i,"Y");
- }else{
- preparedStatement.setString(i,"N");
- }
- }
-
-
-
-
-
-
-
-
- public Boolean getResult(ResultSet resultSet, String columnName) throws SQLException {
- return tranferType(resultSet.getString(columnName)) ;
- }
-
-
-
-
-
-
-
-
- public Boolean getResult(ResultSet resultSet, int i) throws SQLException {
- return tranferType( resultSet.getString(i) );
- }
-
-
-
-
-
-
-
-
- public Boolean getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
- return tranferType(callableStatement.getString(columnIndex));
- }
-
- private Boolean tranferType(String s){
- if("Y".equalsIgnoreCase(s))
- {
- return Boolean.TRUE ;
- }else{
- return Boolean.FALSE;
- }
- }
- }
然后,在Mapper文件中,给需要转换的字段指定该类型转换器mangoBooleanTypeHandler(mangoBooleanTypeHandler为typeAlias,在Mybatis配置文件中定义):
- <resultMap id="customDynamicFieldValueType" type="dynamicFieldValueType">
- <result column="DYNAMIC_FIELD_ID" property="dynamicFieldId" />
- <result column="DYNAMIC_FIELD_VALUE" property="dynamicFieldValue" />
- <result column="DYNAMIC_FIELD_LABEL" property="dynamicFieldLabel" />
- <result column="REQUIRED" property="required" typeHandler="mangoBooleanTypeHandler" />
- </resultMap>
然后我们在Mybatis的配置文件中这样注册它:
Xml代码
- <typeHandlers>
- <typeHandler handler="com.tiantian.mybatis.handler.mangoBooleanTypeHandler"/>
- </typeHandlers>
参考:
https://my.oschina.net/kolbe/blog/508131
http://elim.iteye.com/blog/1847854