现象
表的主键是id bigint,用来存储雪花算法生成的ID。
create table `test` (
`id` bigint not null comment 'id',
`name` varchar(50) comment '名称',
`password` varchar(50) comment '密码',
primary key (`id`)
) engine=innodb default charset=utf8mb4 comment='测试';
使用Long 类型对应数据库ID类型。
import lombok.Data;
@Data
public class Test{
/**
* 用户id
*/
private Long id;
//其他成员变量省略
}
后端断点以JSON数据响应给前端正常。
{
"id": "107481618557435904",
...
}
实际在前端展示
107481618557435904-----------------------107481618557435900
※ 服务端Long类型的id,正常。前端JSON字符串转js对象,接收Long类型的是Number,Number精度是16位(雪花ID是19位),JS的Number数据类型导致精度丢失。
解决如下
- 将数据库表设计的id字段由 Long 类型改成 String 类型,但要考虑实际情况,String 类型做ID,查询性能会下降。
- 前端用String类型的雪花ID保持精度,后端及数据库继续使用Long(BigINT)类型不影响数据库查询执行效率。
- 使用Jackson进行JSON序列化的时候怎么将Long类型ID转成String响应给前端。
package com.liu.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.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
/**
* @ClassName : JacksonConfig
* @Description : 雪花算法ID到前端之后精度丢失问题
* @Author : liunian
* @Date: 2021-06-17 14:20
*/
@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;
}
}