springboot~mybatis枚舉映射

在mybatis和mybatis plus裏,若是你的實體字段是一個枚舉類型,而在數據表裏是整型,這時在存儲時須要進行處理,默認狀況下,會把枚舉的元素名稱拼接到SQL語句裏,而因爲數據表是int類型,因此在插入等操做時,就會出現異常!sql

添加枚舉處理器

MappedTypes(value = {YesOrNo.class})
public class UniversalEnumHandler<E extends Enum<E> & BaseEnum> extends BaseTypeHandler<E> {

  private final Class<E> type;

  /**
   * construct with parameter.
   */
  public UniversalEnumHandler(Class<E> type) {
    if (type == null) {
      throw new IllegalArgumentException("Type argument cannot be null");
    }
    this.type = type;
  }

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType)
      throws SQLException {
    ps.setInt(i, parameter.getCode());
  }

  @Override
  public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
    int code = rs.getInt(columnName);
    return rs.wasNull() ? null : EnumUtils.codeOf(this.type, code);
  }

  @Override
  public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    int code = rs.getInt(columnIndex);
    return rs.wasNull() ? null : EnumUtils.codeOf(this.type, code);
  }

  @Override
  public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    int code = cs.getInt(columnIndex);
    return cs.wasNull() ? null : EnumUtils.codeOf(this.type, code);
  }
}

在配置文件指定處理器

mybatis-plus:
  typeHandlersPackage: cn.pilipa.account.cerebrum.client.enums #處理器所在包,我是把枚舉處理器放在枚舉包裏

定義表明枚舉鍵值的接口

public interface BaseEnum<E extends Enum<?>, T> {

  public Integer getCode();

  public String getText();
}

定義一下枚舉

public enum YesOrNo implements BaseEnum {
  Yes(1, "是"),
  No(0, "否");
  private Integer code;
  private String text;

  YesOrNo(Integer code, String text) {
    this.code = code;
    this.text = text;
  }

  @JsonCreator
  public static YesOrNo jsonCreate(Integer code) {
    return EnumUtils.codeOf(YesOrNo.class, code);
  }

  @Override
  public Integer getCode() {
    return this.code;
  }

  @Override
  public String getText() {
    return this.text;
  }

  @JsonValue
  public Integer getCodeStr() {
    return this.code;
  }

}

在實體中定義枚舉類型字段

/**
   * 是否爲國民.
   */
  private YesOrNo naturalBorn;

生成的SQL語句

==>  Preparing: INSERT INTO employee_info ( id, name, credit_number, status, first_time, tax_code, natural_born ) VALUES ( ?, ?, ?, ?, ?, ?, ? ) 
2019-09-05 16:56:38.991 DEBUG [accounting-client,,,] 92833 --- [           main] c.p.a.c.c.m.EmployeeInfoMapper.insert    : 
==> Parameters: 1169534796253630466(Long), 段會濤(String), 130523199011111219(String), 1(Integer), 2019-09-05(Date), 130523199011111219(String), 0(Integer)

從上面結果中看到,咱們的natural_born對應的值已是int類型了,表示處理器成功了!json

相關文章
相關標籤/搜索