后端返回给前端的id:

1858936203962593281

后端接受到前端发送的id:

1858936203962593300

很明显的数据不一致,在数据库中查询这个id也是不存在的。也就是说,如果想根据id定位到当前的数据进行crud的操作,是找不到该数据的。

注意:如果你用后端接口文档测试或者断点调试,值是没有问题的,问题只会出现在前端。

问题出在雪花算法生成的ID在前端显示时出现了精度丢失。雪花算法生成的ID是64位的长整型(Long),而JavaScript中的Number类型只能精确表示53位的整数。因此,当ID超过16位时,JavaScript会自动将其转换为浮点数,导致精度丢失。

需要在实体类的id字段上加入注解:

@JsonFormat(shape = JsonFormat.Shape.STRING)
private Long id;

当然这样每次创建一个新的实体类,id都要配置就比较麻烦。

可用在config包下全局配置

/**
 * Spring MVC Json 配置
 */
@JsonComponent
public class JsonConfig {

    /**
     * 添加 Long 转 json 精度丢失的配置
     */
    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(module);
        return objectMapper;
    }
}
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐