雪花算法传到前端精度丢失问题
问题:
数据库中id是1465396696468033540 结果传到前端变成1465396696468033500,后面几位精度缺失了
原因:
Number精度是16位(雪花ID是19位的),so:JS的Number数据类型导致的精度丢失
解决办法:
- 直接使用注解把Long类型序列化(与方法2本质是一样的)
-
/** * 防止精度丢失 */ @JsonSerialize(using = ToStringSerializer.class) private Long id;
-
- 前端用String类型的雪花ID保持精度,后端及数据库继续使用Long(BigINT)类型不影响数据库查询执行效率。在Spring Boot应用中,使用Jackson进行JSON序列化的时候怎么将Long类型ID转成String响应给前端?
-
@Configuration public 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; } }
-
- 笨方法:把所有的数据库表设计,id字段由Long类型改成String类型
原文入口:https://www.cnblogs.com/zimug/archive/2020/08/25/13557662.html
一个小小后端的爬行痕迹