现在的位置: 首页 > 编程语言 > 正文

springbootmybatis枚举映射示例代码

2020年02月13日 编程语言 ⁄ 共 2335字 ⁄ 字号 评论关闭

前言

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。

本文标题: spring boot mybatis枚举映射示例代码

以上就上有关springbootmybatis枚举映射示例代码的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.