雪花算法ID,对应的后端Long类型,前端number类型,它们的精度不一样,导致精度丢失
现象
雪花算法得到的ID较长,传到前端后,精度丢失
库中:23754851322302474
后端:23754851322302474
前端:23754851322302470
解决方法
将Long类型转成String,再传给前端
方法一:单个注解@JsonSerialize(using= ToStringSerializer.class)
private Long id;
方法二:统一配置package com.jiawa.wiki.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
/**
* 统一注解,解决前后端交互Long类型精度丢失的问题
* 公众号:甲蛙全栈
* 关联视频课程《Spring Boot + Vue3 前后端分离 实战wiki知识库系统》
* https://coding.imooc.com/class/474.html
*/
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}
—————— THE END ——————
原文链接:http://www.jiawablog.com/detail?id=156521212003094528
甲蛙博客,专注Java全栈技术分享