java - 控制器未填充复合 PK 对象
问题描述
我正在使用 Spring 和 Hibernate。我有一个带有复合主键的学生类。为了实现这一点,我正在使用@Embeddedable
and @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 没有任何意义。这更像是一个实践项目。
解决方案
使用 Json 包装的注解
@JsonUnwrapped
@EmbeddedId
private StudentId studentId;
推荐阅读
- java - Displaying Currency in JSpinner
- c# - How to index list of documents with doc id in ElasticSearch NEST 7.x
- git - Git Reset in VisualStudio : Is --soft equivalent to --mixed here?
- javascript - Displaying Message when no search result found in Angular
- android - 如何检查 Json Response 中的 TypeOf 值?
- sql - 在 SQL Server 中获取上一行和下一行
- laravel - 如何在 laravel 中添加与默认用户类的关系?
- r - 如何从 R 中的池数据中删除特定月份?
- xml - XSL 错误:格式编号图片:被动字符不得出现在子图片中的活动字符之间
- mysql - 如何更改 MySQL Server 8.0 的 root 密码