mybatis 枚举类型使用

liqiancao 2016-06-01

一、首先定义接口,提供获取数据库存取的值得方法,如下:

public interface BaseEnum {
     int getCode();
}
二、定义mybatis的typeHandler扩展类,如下:
package com.camelot.assetcenter.sdk.orm.mybatis;

import com.camelot.assetcenter.sdk.common.BaseEnum;
import com.camelot.openplatform.common.log.Log;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class EnumTypeHandler extends BaseTypeHandler<BaseEnum> {

private final static Logger logger = Log.get(EnumTypeHandler.class);
   private Class<BaseEnum> type;

   private final BaseEnum[] enums;

/**
    * 设置配置文件设置的转换类以及枚举类内容,供其他方法更便捷高效的实现
* @param type 配置文件中设置的转换类
*/
public EnumTypeHandler(Class<BaseEnum> type) {
if (type == null)
throw new IllegalArgumentException("Type argument cannot be null");
      this.type = type;
      this.enums = type.getEnumConstants();
      if (this.enums == null)
throw new IllegalArgumentException(type.getSimpleName()
               + " does not represent an enum type.");
}

@Override
public BaseEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
// 根据数据库存储类型决定获取类型,本例子中数据库中存放INT类型
logger.debug(columnName);
      int i = rs.getInt(columnName);

      if (rs.wasNull()) {
return null;
} else {
// 根据数据库中的code值,定位EnumStatus子类
return locateEnumStatus(i);
}
   }

@Override
public BaseEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
// 根据数据库存储类型决定获取类型,本例子中数据库中存放INT类型
logger.debug(columnIndex+"");
      int i = rs.getInt(columnIndex);
      if (rs.wasNull()) {
return null;
} else {
// 根据数据库中的code值,定位EnumStatus子类
return locateEnumStatus(i);
}
   }

@Override
public BaseEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
// 根据数据库存储类型决定获取类型,本例子中数据库中存放INT类型
logger.debug(columnIndex+"");
      int i = cs.getInt(columnIndex);
      if (cs.wasNull()) {
return null;
} else {
// 根据数据库中的code值,定位EnumStatus子类
return locateEnumStatus(i);
}
   }

@Override
public void setNonNullParameter(PreparedStatement ps, int i, BaseEnum parameter, JdbcType jdbcType)
throws SQLException {
// baseTypeHandler已经帮我们做了parameter的null判断
logger.debug(parameter.getCode()+"=================================");
ps.setInt(i, parameter.getCode());

}

/**
    * 枚举类型转换,由于构造函数获取了枚举的子类enums,让遍历更加高效快捷
* @param code 数据库中存储的自定义code属性
* @return code对应的枚举类
*/
private BaseEnum locateEnumStatus(int code) {
for(BaseEnum status : enums) {
if(status.getCode() ==code ) {
return status;
}
      }
throw new IllegalArgumentException("未知的枚举类型:" + code + ",请核对" + type.getSimpleName());
}

}
三、在mapper文件中的使用:
在使用枚举的地方指定typeHandler,如下:
<select id="queryOverdueDetail" resultMap="assetUserIntegralDetailMap">
   <include refid="selectAllColumns" />
where 1=1
<if test="entity!=null">
      <if test="entity.type != null  and entity.type !=''">
<![CDATA[ and asset_user_integral_detail_.type  = #{entity.type,typeHandler=com.camelot.assetcenter.sdk.orm.mybatis.EnumTypeHandler} ]]>
</if>

      <if test="entity.status != null  and entity.status !=''">
<![CDATA[ and asset_user_integral_detail_.status  = #{entity.status,typeHandler=com.camelot.assetcenter.sdk.orm.mybatis.EnumTypeHandler} ]]>
</if>
      <if test="entity.createTime != null  ">
<![CDATA[ and asset_user_integral_detail_.create_time  < #{overdueTime} ]]>
</if>
   </if>
   <if test="limitCount !=null and limitCount != '' ">
limit #{limitCount}
</if>
</select>
<resultMap id="assetUserIntegralDetailMap" type="assetUserIntegralDetail">
   <result property="userIntegralDetailId" column="user_integral_detail_id" />
   <result property="userIntegralId" column="user_integral_id" />
   <result property="integral" column="integral" />
   <result property="balanceIntegral" column="balance_integral" />
   <result property="type" column="type" typeHandler="com.camelot.assetcenter.sdk.orm.mybatis.EnumTypeHandler"/>
   <result property="businessType" column="business_type" typeHandler="com.camelot.assetcenter.sdk.orm.mybatis.EnumTypeHandler"/>
   <result property="businessId" column="business_id" />
   <result property="source" column="source" typeHandler="com.camelot.assetcenter.sdk.orm.mybatis.EnumTypeHandler"/>
   <result property="shopId" column="shop_id" />
   <result property="status" column="status" typeHandler="com.camelot.assetcenter.sdk.orm.mybatis.EnumTypeHandler"/>
   <result property="createTime" column="create_time" />
   <result property="description" column="description" />
</resultMap>
<if
test="entity.type != null  and entity.type !=''">
<![CDATA[ and asset_user_integral_detail_.type  = #{entity.type,typeHandler=com.camelot.assetcenter.sdk.orm.mybatis.EnumTypeHandler} ]]>
</if>
<if
test="entity.businessType != null  and entity.businessType !=''">
<![CDATA[ and asset_user_integral_detail_.business_type  = #{entity.businessType,typeHandler=com.camelot.assetcenter.sdk.orm.mybatis.EnumTypeHandler} ]]>
</if>
按照以上方式既可以实现枚举类型和mybatis映射

相关推荐