雪花算法傳到前端精度丟失問題


問題:

  數據庫中id是1465396696468033540 結果傳到前端變成1465396696468033500,后面幾位精度缺失了

原因:

  Number精度是16位(雪花ID是19位的),so:JS的Number數據類型導致的精度丟失

解決辦法

  1. 直接使用注解把Long類型序列化(與方法2本質是一樣的)
    1. /**
      * 防止精度丟失
      */
      @JsonSerialize(using = ToStringSerializer.class)
      private Long id;
  2. 前端用String類型的雪花ID保持精度,后端及數據庫繼續使用Long(BigINT)類型不影響數據庫查詢執行效率。在Spring Boot應用中,使用Jackson進行JSON序列化的時候怎么將Long類型ID轉成String響應給前端?
    1. @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;
        }
      
      }
  3. 笨方法:把所有的數據庫表設計,id字段由Long類型改成String類型 

 

原文入口:https://www.cnblogs.com/zimug/archive/2020/08/25/13557662.html

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM