怎么在spring boot中映射mybatis枚举?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
添加枚举处理器
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)
看完上述内容,你们掌握怎么在spring boot中映射mybatis枚举的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。