Solving the problem of loss of precision when converting SpringBoot global configuration Long to String

first way

Simple and crude, change all Long types to String, and change the database to varchar type;

Second way

Create your own configuration class

extends WebMvcConfigurerAdapter has been deprecated, just implement the WebMvcConfigurer interface directly.

@EnableWebMvc
@Configuration
public class WebDataConvertConfig implements WebMvcConfigurer {
         public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
             MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
             ObjectMapper objectMapper = new ObjectMapper();
             /**
                 * Replace the sequence withjsonhour,put alllongbecomestring
                 * becausejsThe number type cannot contain alljava longvalue
                 */
             SimpleModule simpleModule = new SimpleModule();
             simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
             simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
             objectMapper.registerModule(simpleModule);
             jackson2HttpMessageConverter.setObjectMapper(objectMapper);
             converters.add(jackson2HttpMessageConverter);
         }
}

The third way

Using Jackson

@Configuration
public class JacksonConfig {

    /**
     * JacksonGlobal conversionlongThe type isString,solvejacksonWhen serializinglongType missing precision problem
     *
     * @return Jackson2ObjectMapperBuilderCustomizer injected object
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
                jacksonObjectMapperBuilder
                        .serializerByType(Long.class, ToStringSerializer.instance)
                        .serializerByType(Long.TYPE, ToStringSerializer.instance);
            }
        };
    }
}

[Note] Do not add the @EnableWebMvc annotation in this method, otherwise it will cause the serialization of your own configuration to fail.

Baidu: @EnableWebMvc in SpringBoot causes ObjectMapper to fail

Configuration failure caused by incorrect use of @EnableWebMvc _enablewebmvc does not take effect – CSDN Blog

The fourth way (disadvantage: all numeric types will be converted to strings)

Add the following configuration to application.yml:

spring:
     jackson:
     #put allnumberType conversion toStringreturn
         generator:
             write_numbers_as_strings: true

Generally the second or third type is used.