问题描述
在使用MybatisPlus开发的时候,在执行添加功能的时候,使用MP的id生成策略(ASSIGN_ID)生成的id是一个很长的long类型的数字。数字长其实还没事,问题是我后端返回的那串数字和前端拿到的数据不一致,前端axio请求后,ID后面几位的是00
经过研究,MyBatis-Plus 的 ASSIGN_ID 策略使用雪花算法生成一个 19 位的 Long 类型数值。当这个数值传到前端时,由于超过了 JavaScript 中数字的最大范围,导致最后两位始终为 0。
解决方案
第一种方案是,在每个实体类的ID字段上加注解,这种情况是你的项目使用的这个生成策略较少的情况,通过 @JsonSerialize(using = ToStringSerializer.class) 注解,将 ID 的类型转换为 String 类型,从而完整地保留原始数值。
@TableId(type = IdType.ASSIGN_ID) @JsonSerialize(using = ToStringSerializer.class) private Long id;
- 这种解决方案需要在每个 ID 字段上添加注解,可能会比较麻烦
- 建议可以创建一个公共基类实体,其他实体继承这个基类,这样只需要在基类中添加一次注解
第二种方案,做一个全局的配置,将Long类型的转为JSON中的string类型
@Configurationpublic class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
{
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 全局配置序列化返回 JSON 处理
SimpleModule simpleModule = new SimpleModule();
// 如果你有其他类型的转换规则,都写在这里
//JSON Long ==> String
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}
文章评论