Spring Boot读取请求体失败,插入员工数据时字段为null报错
问题详情
我是Java和Spring Boot新手,开发简单REST API插入员工记录到MySQL时遇到以下错误:
@RequestBody => Employee [id=0, firstName=null, lastName=null, email=null] Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : com.saa.springboot.model.Employee.firstName] with root cause org.hibernate.PropertyValueException: not-null property references a null or transient value : com.saa.springboot.model.Employee.firstName at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:111) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
Employee实体类代码
@Data @Entity @Table(name="employees") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "first_name", nullable = false) private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "email") private String email; }
EmployeeController代码
package com.saa.springboot.controller; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.saa.springboot.model.Employee; import com.saa.springboot.service.EmployeeService; @RestController @RequestMapping("/api/employees") public class EmployeeController { private EmployeeService employeeService; public EmployeeController(EmployeeService employeeService) { super(); this.employeeService = employeeService; } @PostMapping() public ResponseEntity<Employee> saveEmployee(@RequestBody Employee employee) { System.out.println("@RequestBody => " + employee.toString()); return new ResponseEntity<Employee>(employeeService.saveEmployee(employee), HttpStatus.CREATED); } }
应用配置文件
spring.datasource.url = jdbc:mysql://localhost:3306/ems_db?useSSL=false spring.datasource.username = root spring.datasource.password = pwd spring.jpa.database-platform = org.hibernate.dialect.MySQLDialect spring.jpa.generate-ddl = true spring.jpa.hibernate.ddl-auto = update
Curl请求
curl -i -H "Accept: application/json" -H "Content-Type:application/json" -X POST --data "{\"firstName\": \"john\", \"lastName\": \"cena\"}" "http://localhost:8080/api/employees"
从打印日志可以看到,@RequestBody读取的所有字段值都是null:
@RequestBody => Employee [id=0, firstName=null, lastName=null, email=null]
Postman测试也出现同样错误,求指导。
解决方案
问题核心是Jackson无法为Employee实体类注入JSON属性值,导致所有字段为null,进而触发数据库非空约束报错。主要原因及解决办法如下:
1. 检查Lombok插件与依赖
你用了@Data注解自动生成getter/setter,但如果IDE未安装Lombok插件,或项目未引入Lombok依赖,编译后的实体类不会生成setter方法,Jackson无法设置属性值:
- 安装IDE Lombok插件:比如IntelliJ IDEA需在
Settings > Plugins中搜索安装Lombok插件,重启IDE生效。 - 确认依赖配置:
pom.xml中添加Lombok依赖:
Gradle项目则添加:<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok'
2. 验证实体类的setter方法
编译项目后,查看target/classes(Maven)或build/classes(Gradle)下的Employee.class文件,确认是否存在setFirstName()、setLastName()等方法。若不存在,说明Lombok未生效,回到第一步排查。
3. 替代方案:手动添加getter/setter
如果不想依赖Lombok,可直接在Employee类中手动编写getter和setter方法:
@Entity @Table(name="employees") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "first_name", nullable = false) private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "email") private String email; // Getters public long getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getEmail() { return email; } // Setters public void setId(long id) { this.id = id; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setEmail(String email) { this.email = email; } // 手动添加toString方法(可选) @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; } }
4. 确认JSON字段匹配
你的curl请求中firstName、lastName与实体类字段名完全匹配(大小写敏感),这部分无需调整。
内容的提问来源于stack exchange,提问作者Satishakumar Awati
相关产品推荐
相关产品推荐

