【问题标题】:Composite PK object not being populated by controller控制器未填充复合 PK 对象
【发布时间】: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 没有任何意义。这更像是一个实践项目。

【问题讨论】:

    标签: java spring hibernate


    【解决方案1】:

    使用 Json 封装的注解

      @JsonUnwrapped
      @EmbeddedId
      private StudentId studentId;
    

    【讨论】:

      【解决方案2】:

      我可以通过查看 this question 来解决此问题。

      唯一的变化是添加了@JsonUnwrapped 注释。

      @Data
      @Entity
      @Table(name = "students")
      @NoArgsConstructor
      @AllArgsConstructor
      public class Student {
      
          @JsonUnwrapped // <= This piece
          @EmbeddedId
          private StudentId studentId;
      
          private int age;
      
          @Data
          @Embeddable
          @NoArgsConstructor
          @AllArgsConstructor
          public static class StudentId implements Serializable {
              @Column(name = "id")
              private Long id;
      
              @Column(name = "name")
              private String name;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-12
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 2013-08-30
        • 1970-01-01
        • 2011-09-06
        相关资源
        最近更新 更多