【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;

    }
}
相关推荐
Csvn1 分钟前
content-visibility: auto —— 让浏览器跳过离屏渲染的性能黑科技
前端
小鹰信息技术服务部2 分钟前
Edge安装包MicrosoftEdgeSetup.exe无法运行,点击没反应
前端·edge
webkubor1 小时前
一次前端生产白屏复盘:旧 HTML、Hash 资源和 MIME type text/html
前端·前端工程化
咩咩啃树皮1 小时前
第63篇【终极整合巨作】从零手写原生中后台管理系统|整合62篇全部前端知识点|从头到尾完整架构+全功能逻辑
前端·架构
凌云拓界1 小时前
NodeVerdict:Node.js 原生诊断数据可视化工具
信息可视化·架构·typescript·开源·node.js·github·bug
还是鼠鼠2 小时前
【Spring AI智能体实战 02】Spring Boot 3.4整合Spring AI:项目创建与依赖配置
java·人工智能·spring boot·maven·spring ai
Highcharts2 小时前
用Highcharts如何动态向一个序列添加点-示列讲解
前端
weixin_431600442 小时前
做 Agent 会用到的 Node API(4):取消与 AbortController
前端·学习·ai·agent·ai编程
JiaLin_Denny3 小时前
Vue3中ref和reactive用法与双向数据绑定
前端·javascript·vue.js
用户2181697049303 小时前
Flutter(十)Container Center Align
前端