2
我有以下类别:与外键单向一对多不会插入到表
@Entity
@Table(name = "PARENT")
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "PARENT_ID", unique = true, nullable = false, insertable = true, updatable = true)
private Long parentId;
@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinColumn(name="PARENT_ID", nullable = false)
private List<Child> children;
public Parent(List<Child> children) {
this.children = children;
}
..
... Getters\Setters
}
@Entity
@Table(name = "CHILD")
public class Child {
@Id
@Column(name = "TYPE", unique = false, nullable = false)
private String type;
@Column(name = "RANK", unique = false, nullable = false, insertable = true, updatable = false)
private String rank;
}
的“PARENT_ID”是“子”表的外键。所以它使“CHILD”表有两列形成PRIMARY_KEY。
我执行以下插入:
List<Child> children = new LinkedList<Child>();
children.add(new Child("1,2,3,4"));
children.add(new Child("1,2,3,4"));
Parent parent = new Parent(children);
session.save(parent);
如果两个表是空的它创建的“父”和“孩子”的,如果“儿童”的条目中已经存在分配PARENT_ID!但正确它执行更新而不是插入!
注意两个“孩子”都有相同的“TYPE”(“1,2,3,4”),但他们应该有不同的“PARENT_ID”。
我在这里丢失什么?
谢谢!
是的,可能的工作,但现在它双向关联,这是很好的,但增加了不必要的编码的复杂性。 – Shvalb
是的,您可能是对的,Embedded和Embeddable可能是更好的方法。但是,您将使用此的上下文更重要 – amitsalyan