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”表中的外键。因此它使“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 正确创建“父”和“子”!但是如果表中已经存在“子”条目,它会执行更新而不是插入!

请注意,两个“孩子”具有相同的“类型”(“1,2,3,4”),但它们应该具有不同的“PARENT_ID”。

我在这里想念什么???

谢谢 !

4

1 回答 1

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
于 2013-07-08T03:58:18.320 回答