2013-07-07 37 views
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”。

我在这里丢失什么?

谢谢!

回答

0

在你的孩子你需要有父母的一个实例,我相信你错误地放在你的父类的JoinColumn应该在你的子类中。而且这个构造函数在你的父类中是不需要的。

父类应该是这个样子:

@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) 

} 

你的孩子类应该是这样的:

@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 
+0

是的,可能的工作,但现在它双向关联,这是很好的,但增加了不必要的编码的复杂性。 – Shvalb

+0

是的,您可能是对的,Embedded和Embeddable可能是更好的方法。但是,您将使用此的上下文更重要 – amitsalyan