【发布时间】:2021-07-15 16:27:53
【问题描述】:
我正在使用 Spring 和 Hibernate。我有一个带有复合主键的学生类。为此,我使用@Embeddedable 和@EmbeddedId。但是,在我的控制器中,这些值不会自动填充,值是 null。
Student.java
@Data
@Entity
@Table(name = "students")
@NoArgsConstructor
@AllArgsConstructor
public class Student {
@EmbeddedId
private StudentId studentId;
@Data
@Embeddable
@NoArgsConstructor
@AllArgsConstructor
public static class StudentId implements Serializable {
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
}
}
StudentController.java
@RestController
@RequestMapping(path = "api/v1/student")
public class StudentController {
private StudentService studentService;
@Autowired
public void setStudentService(StudentService studentService) {
this.studentService = studentService;
}
@PostMapping
public void addStudent(@RequestBody Student student) {
System.out.println(student); // Prints Student(studentId=null)
// this.studentService.addStudent(student);
}
}
我需要做些什么来自动填充 Student 对象中的值。
注意:我同意这里的复合 PK 没有任何意义。这更像是一个实践项目。
【问题讨论】: