Mybatis 枚举自定义转换

定义Hander 实现

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import xxx.CouponProvider;

@MappedJdbcTypes(value = {JdbcType.TINYINT})
@MappedTypes({CouponProvider.class})
public class EnumTypeHander extends BaseTypeHandler {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, CouponProvider parameter,
      JdbcType jdbcType) throws SQLException {
    // 枚举类转换到number类型,设置到Statement中
    ps.setInt(i, parameter.getNumber());
  }

  @Override
  public CouponProvider getNullableResult(ResultSet rs, String columnName) throws SQLException {
    // 将Number数值转到到枚举类型
    return CouponProvider.forNumber(rs.getInt(columnName));
  }

  @Override
  public CouponProvider getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    // 将Number数值转到到枚举类型
    return CouponProvider.forNumber(rs.getInt(columnIndex));
  }

  @Override
  public CouponProvider getNullableResult(CallableStatement cs, int columnIndex)
      throws SQLException {
    // 将Number数值转到到枚举类型
    return CouponProvider.forNumber(cs.getInt(columnIndex));
  }

}

 
  

Mybatis-mapper.xml 定义

	
	
	INSERT INTO promotion (name,type)
	VALUES(#{name},#{type,javaType=xxx.EnumType,jdbcType=TINYINT,typeHandler=xxx.EnumTypeHander})
	
	
		
		
	
	


你可能感兴趣的:(java)