Nesting multiple entities hibernate giving issues

非 Y 不嫁゛ 提交于 2021-02-11 18:19:44

问题


I am having an issue with mapping a 3rd level entity please consider the following code:

Parent Entity :

@Entity
@Table(name = "Tree")
public class Tree { 


@Id
@Column(name="Tree_Id") 
@GeneratedValue(strategy = GenerationType.Identity)  
private Integer id;

@OneToMany(mappedBy = "parentTree", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Branch> branches;

//Getters And Setters

public Branch addBranch(Branch branch) {
getBranch().add(branch);

branch.setTree(this);

return branch;

}

// remove function to remove branches from tree 
}

Child Class :

`@Entity
@Table(name = "Branch")
public class Branch {

@Id
@Column(name="Branch_Id") 
@GeneratedValue(strategy = GenerationType.Identity)
private Integer id;

@ManyToOne(fetch = FetchType.Lazy)
@JoinColumn(name = "TreeId")
private Tree parentTree;

@OneToMany(mappedBy = "parentBranch", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Leaf> leaves;

//Getters And Setters

public Leaf addLeaves(Leaf leaves) {
getLeaf().add(leaves);

leaves.setBranch(this);

return leaves;
}

// remove function for leaves to remove them from set
}`

Now when saving the Tree class through the cascade whatever was added or removed from the Set will be treated accordingly. If the child is new and the foreign key is not populated before persisting, hibernate will handle it based on the parent PK.

Here is the Entity that is giving me issues:

@Entity
@Table(name = "Leaf")
public class Leaf {

@Id
@Column(name="Leaf_Id") 
@GeneratedValue(strategy = GenerationType.Identity)
private Integer id;

@ManyToOne(fetch = FetchType.Lazy)
@JoinColumn(name = "Branch_Id")
private Branch parentBranch;


// getters and setters

The problem I am experiencing is awkward to say the least, but when there is no record for this class hibernate will work it out and persist this entity with the parents key. The issue I'm having now is if the Leaf record exist for the child when I try to persist hibernate doesn't assign this class its Foreign key. This usually happens on an update. Its strange that hibernate will work this out on the insert but not on the update. It works this out for two levels though when we go from just tree to branch. Does any one have an answer to this?

来源:https://stackoverflow.com/questions/60132684/nesting-multiple-entities-hibernate-giving-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!