spring boot mybatis枚举映射示例代码

网友投稿 308 2022-12-28


spring boot mybatis枚举映射示例代码

前言

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

添加枚举处理器

MappedTypes(value = {YesOrNo.class})

public class UniversalEnumHandler & BaseEnum> extends BaseTypeHandler {

private final Class type;

/**

* construct with parameter.

*/

public UniversalEnumHandler(Class 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(EwyQPIi, 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

pubhttp://lic 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, 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 http://DEBUG [accounting-client,,,] 92833 --- [ main] c.p.a.c.c.m.EmployeeInfoMapper.insert :

==> Parameters: 1169534796253630466(Long), http://段会涛(String), 130523199011111219(String), 1(Integer), 2019-09-05(Date), 130523199011111219(String), 0(Integer)

从上面结果中看到,我们的natural_born对应的值已经是int类型了,表示处理器成功了!

总结

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:异构微服务网关(微服务网关集群)
下一篇:Java方法的参数传递机制实例详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~