Issue
I'm working with Spring and Hibernate. I have a Student class with a composite primary key. To achieve this, I am using @Embeddedable
and @EmbeddedId
. However, in my controller, the values are not populating automatically and the value comes as 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);
}
}
What do I need to do to automatically populate the values in the Student object.
Note: I agree a composite PK here doesn't really make sense. This is more of a practice project.
Solution
I was able to fix this by looking at this question.
The only change was adding the @JsonUnwrapped
annotation.
@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;
}
}
Answered By - NiceOne
Answer Checked By - David Goodson (JavaFixing Volunteer)