一对多休眠

时间:2012-05-28 22:57:38

标签: hibernate jsf-2 one-to-many

我有这种关系一对多。 这是我的一张桌子。

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插入带有MANY容器的新容器。 我会试试这个:

...
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 个答案:

答案 0 :(得分:1)

当您在mappedBy = "container"实体中指定Container时,关系的所有者就是Images实体。这意味着hibernate将确定Container和{之间的关系{1}}实体使用Images

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

要解决此问题,您应该设置container实例的Image属性:

Container c = new Container();
img1.setContainer(c);
img2.setContainer(c); 
session.save(c);
相关问题