原由
由于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;
}
}
网友评论