我有以下课程:
@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”表中的外键。所以它使“CHILD”表有2列形成它的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!, BUT 来正确创建“父”和“子”,如果表中已存在“子”条目,则表示执行更新而不是插入! / p>
注意两个'孩子'都有相同的“TYPE”(“1,2,3,4”),但他们应该有不同的“PARENT_ID”。
我在这里错过了什么????
谢谢!
答案 0 :(得分:0)
在您的孩子中,您需要拥有父母的实例,并且我相信您错误地放置了您的子类中的JoinColumn,该类应该在您的子类中。在您的Parent类中不需要构造函数。
父类应该类似于:
@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;
@Embedded
private Child children;
..
... Getters\Setters (MAke sure you have the getter setter for children as well)
}
您的Child类应该是这样的:
@Embeddable
@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;
//getter and setters