Reputation: 1185
I am performing a parent child save using CASCADE.PERSIST
@Entity
@Table(name = "parent")
public class Parent extends AbstractAuditingEntity{
@OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.PERSIST)
@JoinColumn(name = "parent_id",nullable = false)
private List<Child> children;
}
@Entity
@Table(name = "child")
public class Child extends AbstractAuditingEntity{
@Column(name = "parent_id", insertable=false, updatable=false)
private Long parentId;
}
When I save the parent ,the child also gets saved along with the foreign key.
parent = parentRepository.save(parent);
But the entity that is returned from the repository does not have the foriegn key set in the child.
child.getParentId() is null .
Is there anyway I can get it done ?
Tried setting the parent in the child but same problem exists
@Entity
@Table(name = "child")
public class Child extends AbstractAuditingEntity{
@ManyToOne
@JoinColumn(name="parent_id",nullable = false,insertable=false,updatable=false)
private Queue queue;
}
Though this is a not a critical issue ( i can set it manually from the parent ) - Just wanted to be sure If I am doing it right.
Upvotes: 0
Views: 1440
Reputation: 1185
As pointed out by JB Nizet , the bidrectional mapping was incorrect.
This has been corrected as per the below link and it worked fine
https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/
Upvotes: 1
Reputation: 36103
There is no magic happen on save. That means if you don't set parentId then this field is null. You have to set this on your own.
When you read the data using find or with a query then the field will be set by JPA.
Upvotes: 0