Spring Boot连接H2数据库插入数据为null问题求助
Spring Boot新增接口字段为null问题排查方案
1. 确认Lombok注解是否正常生效
你的Customer实体类使用了@Setter、@Getter注解,但如果Lombok未正确配置,会导致setter方法无法生成,Jackson无法将JSON数据映射到实体字段:
- 检查Maven/Gradle依赖是否引入Lombok:
Maven依赖示例:<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> - 确认IDE已安装Lombok插件,并开启注解处理功能(比如IntelliJ IDEA需在设置中开启"Enable annotation processing")。
- 查看编译后的
Customer类文件,确认是否生成了setName()、setAge()、setLocation()等方法。
2. 检查请求JSON的字段匹配性
Postman发送的JSON字段名必须与实体类字段名大小写完全一致,示例正确JSON格式:
{ "name": "张三", "age": 25, "location": "北京" }
若JSON字段使用Name、Age等大小写不一致的命名,会导致字段映射失败,最终存入数据库的值为null。
3. 验证请求头配置
在Postman发送请求时,必须设置Content-Type请求头为application/json,否则Spring无法识别请求体为JSON格式,@RequestBody无法正确解析数据。
4. 临时调试定位问题
在saveCustomer方法中添加日志打印,确认接收到的Customer对象是否已正确赋值:
@PostMapping("/customers") public ResponseEntity<Customer> saveCustomer(@RequestBody Customer customer) { try { System.out.println("接收的Customer数据:" + customer.toString()); return new ResponseEntity<>(customerRepo.save(customer), HttpStatus.CREATED); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } }
如果打印结果中name、age、location均为null,说明是请求解析环节出问题;如果打印有值但数据库存为null,再排查JPA配置(你的当前配置无明显问题,概率较低)。
内容的提问来源于stack exchange,提问作者infq
相关产品推荐
相关产品推荐

