I send a request to my endpoint with a nested entity. But getChild always returns null
when I parse the requestbody with Parent.
My Entities:
@Entity
public class Parent {
@Id
@GenericGenerator(name = "uuid-gen", strategy = "uuid2")
@GeneratedValue(generator = "uuid-gen")
@Type(type = "pg-uuid")
private UUID id;
@Column(nullable = false)
private String name;
@JsonBackReference(value="child")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(foreignKey = @ForeignKey(name = "child_id"))
private Child child;
public Parent() {
}
public Card(UUID id, String name, Child child) {
this.id = id;
this.name = name;
this.child = child;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setChild(Child child) {
this.child = child;
}
public Child getChild() {
return child;
}
}
@Entity
public class Child {
@Id
@GenericGenerator(name = "uuid-gen", strategy = "uuid2")
@GeneratedValue(generator = "uuid-gen")
@Type(type = "pg-uuid")
private UUID id;
@Column(nullable = false)
private String name;
@JsonManagedReference(value="child")
@OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.ALL)
private List<Parent> parents;
public Child() {
}
public Child(UUID id, String name, List<Parent> parents) {
this.id = id;
this.name = name;
this.parents = parents;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Parent> getParents() {
return parents;
}
public void setParents(List<Parent> parents) {
this.parents = parents;
}
}
I make a POST request to /parents
to create the parent but I have a child which is not created yet but I want to create them together and link them.
The request I send:
{
"name": "Your name",
"child" : {
"name": "Child name"
}
}
What I would expect:
{
"id": "uuid",
"name": "Your name",
"child" : {
"id": "childuuid"
"name": "Child name"
}
}
But what I get is:
{
"id": "uuid",
"name": "Your name"
}
My Controller:
@RequestMapping(value = "/parents", method = RequestMethod.POST)
public Card createParent(
@RequestBody Parent parent
) {
Child child = parent.getChild(); // always null :(
....do something to create both child and parent
return parentService.create(parent);
}