2012-05-28 165 views
0

我有这种关系一对多。 这是我的ONE桌子。一对多休眠

private Set<Images> imagesContainer = new HashSet<Images>(0); 

@OneToMany(fetch = FetchType.LAZY, mappedBy = "container") 
public Set<Images> getImagesContainer() { 
    return this.imagesContainer; 
} 

public void setImagesContainer(Set<Images> imagesContainer) { 
    this.imagesContainer = imagesContainer; 
} 

这是我这么表:

private Container container; 

@ManyToOne(fetch = FetchType.LAZY) 
@JoinColumn(name = "id_container", nullable = false) 
public Container getContainer() { 
    return this.container; 
} 

public void setContainer(Container container) { 
    this.container = container; 
} 

我怎样才能插入,与Hibernate,许多集装箱一个新的容器。 我会试试这个:

... 
Set<Images> images=new HashSet<Images>(); 
images.add(img1); 
images.add(img2); 

Container c = new Container(); 
c.setImagesContainer(images); 
.... 

@Override 
@Transactional(propagation=Propagation.REQUIRED) 
public void save(Container c){ 
    getHibernateTemplate().save(c); 
} 

不要工作!!!我得到了“嵌套的例外是org.hibernate.exception.DataException:无法插入:” ......

回答

1

当您在Container实体指定mappedBy = "container",关系的所有者是Images实体。那意味着,Hibernate会确定使用image.getContainer()

因为你没有设置任何容器实例所有images实例的容器属性在您的代码段,image.getContainer()回报NULL,因此hibernate会认为所有的image实例是ContainerImages实体之间的关系不与任何关联实例。它会将NULL插入Container表的id_container列,该列不允许NULL(nullable = false),因此会发生错误。

为了解决这个问题,你应该设置Image实例的container属性:别人的问题发生

Container c = new Container(); 
img1.setContainer(c); 
img2.setContainer(c); 
session.save(c); 
+0

错误。我使用您的解决方案或我的解决方案:容器中有1条记录,图像中有0条记录,没有错误。 – enfix

+0

PS:容器没有ID,因为这是一个INSERT,而不是UPDATE – enfix