JPA存入数据库的均为null,无法正常保存数据(无DTO场景)
JPA保存数据时存入null值的问题排查与解决
问题描述
我尝试将数据保存到数据库,但JPA并未存入预期数据,而是存入了null值。日常开发中我通常会用DTO处理这类操作,但当前是小型项目,希望不借助DTO完成数据保存。以下是相关代码及配置:
实体类(Entity)
@Setter @Getter @Entity @AllArgsConstructor @NoArgsConstructor public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String surname; private String department; @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable(name = "STUDENT_COURSE_TABLE", joinColumns = { @JoinColumn(name="student_id",referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "couse_id",referencedColumnName = "id") }) @JsonManagedReference private Set<Course> courses; }
DAO层
@Repository public interface StudentRepository extends JpaRepository<Student, Long> { }
Controller层
@RestController @RequestMapping("/api") public class StudentCourseController { private final StudentRepository studentRepository; private final CourseRepository courseRepository; public StudentCourseController(StudentRepository studentRepository, CourseRepository courseRepository) { this.studentRepository = studentRepository; this.courseRepository = courseRepository; } @PostMapping public Student addStudent (Student student){ return studentRepository.save(student); } }
application.properties配置
spring.jpa.show-sql = true spring.jpa.hibernate.ddl-auto = update spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
问题原因及解决方案
1. 缺少请求体绑定注解(核心原因)
你的addStudent方法中的Student参数没有添加@RequestBody注解,Spring无法将前端发送的JSON请求体转换为Student对象,导致所有字段默认是null。
修正代码:
@PostMapping public Student addStudent (@RequestBody Student student){ return studentRepository.save(student); }
2. 请求参数与实体类字段不匹配
检查前端发送的JSON字段名是否和Student实体类的字段完全一致(例如实体类是name,前端不能传username;实体类是surname,前端不能传lastName)。
示例正确的请求JSON:
{ "name": "张三", "surname": "张", "department": "计算机学院", "courses": [{"name": "Java编程"}] }
3. 请求Content-Type错误
确保前端请求的Content-Type设置为application/json,否则Spring无法正确解析JSON格式的请求体。
4. 多对多关联的拼写错误(潜在问题)
你的关联表配置中,inverseJoinColumns的name写错了,应该是course_id而非couse_id,这个错误会导致关联表无法正确创建,后续查询关联数据会出现问题,建议修正:
@JoinColumn(name = "course_id",referencedColumnName = "id")
内容的提问来源于stack exchange,提问作者Lamvegan
相关产品推荐
相关产品推荐

