您好,登錄后才能下訂單哦!
springboot中怎么利用mybatis實(shí)現(xiàn)枚舉映射,相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
添加枚舉處理器
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; }}
在實(shí)體中定義枚舉類型字段
/** * 是否為國(guó)民. */ private YesOrNo naturalBorn;
生成的SQL語(yǔ)句
==> 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), 段會(huì)濤(String), 130523199011111219(String), 1(Integer), 2019-09-05(Date), 130523199011111219(String), 0(Integer)
看完上述內(nèi)容,你們掌握springboot中怎么利用mybatis實(shí)現(xiàn)枚舉映射的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。