美文网首页Java-Spring
Spring-Java对象属性由驼峰(CamelCase)转成蛇

Spring-Java对象属性由驼峰(CamelCase)转成蛇

作者: yusher | 来源:发表于2020-08-28 11:59 被阅读0次

    原由

    由于Java语言偏向于使用驼峰式命名,如columnA,然而数据库(MySQL)表字段一般使用蛇式命名,如column_a,且前端一般也是使用数据库的字段格式进行交互。因此参数传递和返回就需要对驼峰和蛇式的参数进行转化。

    解决方案

    引入com.fasterxml.jackson.core

    ...
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.11.2</version>
    </dependency>
    ...
    

    返回结果处理

    • 配置
    # application.properties
    spring.jackson.property-naming-strategy=SNAKE_CASE
    
    • 数据类
    ...
    @Data
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class TestDTO implements Serializable {
        private static final long serialVersionUID = 1L;
      
        private Integer id;
        
        private String userName;
          
        private Integer createTime;
    }
    

    Tips: JsonInclude注解可以过滤为null的数据

    参数处理

    • 注入ObjectMapper
    @RestController
    public class TestController {
        @Autowired
        private ObjectMapper objectMapper;
    }
    
    • 数据转换
    @RestController
    public class TestController {
        @AutoWired
        private TestService testService;
        ...
        @GetMapping("/test")
        public void index(@RequestParam Map<String, Object> params) {
            TestForm testForm = objectMapper.convertValue(params, TestForm.class);
            testService.index(testForm);
        }
        ...
    }
    
    • 参数验证
    ...
    @Service
    @Validated
    public class TestServiceImpl implements TestService {
        private static final Logger logger = LoggerFactory.getLogger(TestServiceImpl.class);
    
        @AutoWired
        private final TestMapper testMapper;
          
        @Override
        public List<TestModel> index(@Valid TestForm params) {
            List<TestModel> tests = testMapper.selectByParams(params);
            return tests;
        }
    }
    

    相关文章

      网友评论

        本文标题:Spring-Java对象属性由驼峰(CamelCase)转成蛇

        本文链接:https://www.haomeiwen.com/subject/ucnksktx.html