SpringBoot Long类型精度丢失

说明:数据设计使用bigint 类型作为主键,Java后台使用Long 类型进行接收。在浏览器调用接口数据的时候数值ID发生变化精度丢失。postman不会出现这种问题。后经查询问题如下:

  • javascript 的 Number 类型最大长度是17位
  • mysql 使用bigint 类型长度是20位;
@Configuration
public class JsonHttpMessageConvert{

    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        //通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化。
        //JsonInclude.Include.NON_NULL 属性为NULL 不序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //jackson中自定义处理序列化和反序列化
        SimpleModule module = new SimpleModule();
        //Method for adding serializer to handle values of specific type.
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        //register the module with the object-mapper
        objectMapper.registerModule(module);
        return objectMapper;
    }

}

这里采用Mybatis Plus,默认ID生成策略

MyBatis-Plus默认的主键策略:ID_WORKER 全局唯一ID(内部由雪花算法实现)

可通过自增策略设置避免ID过长

要想主键自增需要配置如下主键策略:
需要在创建数据表的时候设置主键自增
实体字段中配置 @TableId(type = IdType.AUTO)

@TableId(type = IdType.AUTO)
private Long id;

要想影响所有实体的配置,可以设置全局主键配置:

#全局设置主键生成策略
mybatis-plus.global-config.db-config.id-type=auto

 

你可能感兴趣的:(SpringBoot)