我在映射第3级实体时遇到问题,请考虑以下代码:
父实体:
@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
}
儿童班:
`@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
}`
现在,通过级联保存Tree类时,将从集合中添加或删除的所有内容都将进行相应处理。如果孩子是新孩子,并且在持久之前未填充外键,则hibernate将基于父PK处理它。
这是给我一些问题的实体:
@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
我遇到的问题至少可以说很尴尬,但是当没有此类的记录时,hibernate会解决该问题并使用父键持久化此实体。我现在遇到的问题是,当我尝试保持休眠状态时,如果孩子存在Leaf记录,则不会为此类分配其外键。这通常在更新时发生。休眠将在插入而不是在更新上解决这个问题很奇怪。尽管当我们从树到分支时,它可以在两个层次上实现。有人对此有答案吗?