問題:
數據庫中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