当前位置: 移动技术网 > IT编程>开发语言>Java > springboot~mybatis枚举映射

springboot~mybatis枚举映射

2019年09月05日  | 移动技术网IT编程  | 我要评论

在mybatis和mybatis plus里,如果你的实体字段是一个枚举类型,而在数据表里是整型,这时在存储时需要进行处理,默认情况下,会把枚举的元素名称拼接到sql语句里,而由于数据表是int类型,所以在插入等操作时,就会出现异常!

添加枚举处理器

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类型了,表示处理器成功了!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网