解决雪花算法ID到前端之后丢失精度问题

一、现象

1、表的主键是id bigint,用来存储雪花算法生成的ID。

CREATE TABLE `user` (
  `id` bigint(32) NOT NULL COMMENT '用户id',
	...
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='用户表';

2、使用Long 类型对应数据库ID类型。

import lombok.Data;

@Data
public class User {
    /**
     * 用户id
     */
    private Long id;
    //其他成员变量省略
}

3、后端断点以JSON数据响应给前端正常。

    {
      "id": "1352166380631257089",
       ...
    }

二、实际问题

1352213368413982722   ------>   1352213368413982700

※ 服务端Long类型的id,正常。前端JSON字符串转js对象,接收Long类型的是Number,Number精度是16位(雪花ID是19位),JS的Number数据类型导致精度丢失。

三、解决问题

1、将数据库表设计的id字段由 Long 类型改成 String 类型,但要考虑实际情况,String 类型做ID,查询性能会下降。

2、前端用String类型的雪花ID保持精度,后端及数据库继续使用Long(BigINT)类型不影响数据库查询执行效率。

Spring Boot应用

方案:实体id主键上加入注解:@JsonFormat(shape = JsonFormat.Shape.STRING)

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

@Data
public class User {
    /**
     * 用户id
     */
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private Long id;
    //其他成员变量省略
}

方案:使用Jackson进行JSON序列化的时候怎么将Long类型ID转成String响应给前端。

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;

@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;
    }
}

 

转载请注明出处:BestEternity亲笔。

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值