首页 > 解决方案 > 控制器未填充复合 PK 对象

问题描述

我正在使用 Spring 和 Hibernate。我有一个带有复合主键的学生类。为了实现这一点,我正在使用@Embeddedableand @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);
    }
}

我需要做什么来自动填充学生对象中的值。

注意:我同意这里的复合 PK 没有任何意义。这更像是一个实践项目。

标签: javaspringhibernate

解决方案


使用 Json 包装的注解

  @JsonUnwrapped
  @EmbeddedId
  private StudentId studentId;

推荐阅读