【BUG】SpringBoot项目Long类型数据返回前端精度丢失问题

问题描述

后端再给前端返回数据,使用Long类型的时候存在精度丢失问题。

原因分析:

分布式项目中广泛使用雪花算法生成ID作为数据库表的主键,Long类型的雪花ID有19位,而前端接收Long类型用的是number类型,但是number类型的精度只有16位。这就导致雪花ID传到前端会出现精度丢失。


解决方案:

通过Jackson序列化转String

java 复制代码
@Configuration
public class SerializerConfig {
    /**
     * Long类型前端精度丢失问题,序列化时转String
     * @param mapperBuilder
     * @return
     */
    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder mapperBuilder) {
        ObjectMapper build = mapperBuilder.createXmlMapper(false).build();
        build.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        build.registerModule(module);
        return build;

    }
}
相关推荐
yinuo7 分钟前
UniApp+Vue3多分包引入同一 npm 库被重复打包至 vendor 的问题分析与解决
前端
码界奇点19 分钟前
Spring Web MVC构建现代Java Web应用的基石
java·前端·spring·设计规范
yinuo38 分钟前
UniApp + Vue3 使用 marked 报错:SyntaxError /[\p{L}\p{N}]/u 问题分析与解决
前端
大前端helloworld1 小时前
前端梳理体系从常问问题去完善-框架篇(Vue2&Vue3)
前端·javascript·面试
编啊编程啊程1 小时前
兼职管理平台
java·spring boot·rpc·dubbo·nio
小墨宝1 小时前
web前端学习LangGraph
前端·学习
南囝coding1 小时前
React 19.2 重磅更新!这几个新特性终于来了
前端·react.js·preact
Dajiaonew1 小时前
Vue3 + TypeScript 一篇文章 后端变全栈
前端·javascript·typescript
陈一Tender2 小时前
JavaWeb后端实战(IOC+DI)
java·spring boot·spring
广州华水科技2 小时前
GNSS与单北斗变形监测一体机在基础设施安全中的应用分析
前端