Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用hibernate保存父表时在外键中插入Null_Java_Hibernate - Fatal编程技术网

Java 使用hibernate保存父表时在外键中插入Null

Java 使用hibernate保存父表时在外键中插入Null,java,hibernate,Java,Hibernate,我试图用Hibernate保存一个表。 父表与其子表具有一对多关系。 父表POJO有其子表POJO的集合 当我保存父表时,数据也被插入到它的子表中,但它的外键不为NULL 下面是我的代码: 家长: 休眠服务: public class HibernateSave { public static void main(String[] args) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory

我试图用Hibernate保存一个表。 父表与其子表具有一对多关系。 父表POJO有其子表POJO的集合

当我保存父表时,数据也被插入到它的子表中,但它的外键不为NULL

下面是我的代码: 家长:

休眠服务:

public class HibernateSave {
public static void main(String[] args) {
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    Session session = sessionFactory.openSession();

            Transaction tx1 = session.beginTransaction();

    Parent parent = new Parent();
            Child child1 = new Child();
            parent.setName("Name");
            child1.setComments("Hey");
            //child1.setParentid(parent);
            List<Child> childs = new ArrayList<Child>();
            childs.add(child1);


            parent.setChildCollection(childs);

            System.out.println("parent Saved id="+session.save(parent));
            tx1.commit();
    session.flush(); //address will not get saved without this
    System.out.println("*****");



} }
但我在想,这是否可以避免。我希望有别的方法,我不需要把我的每个孩子都映射到他们的父母


Kinldy帮助以及您是否可以解释。

如果您更新双向关系的一端,您还必须更新它的另一端,因为维护域模型的正确状态是应用程序的责任

您可以做的一件事是在Parent中创建一个方法来添加child:

public void addChild(Child child) {
    childCollection.add(child);
    child.setParentId(this);
}
或/和儿童相反:

public void setParent(Parent parent) {
    parent.getChildCollection().add(this);
    this.setParentId(parent)
}
(代码没有必要的空检查等,但应给出想法)

从而使代码不那么容易出错(即忘记更新关系的另一端)


似乎还有一个字节码增强功能,它将向实体的类文件中添加类似的代码,但我对这一功能的效果没有经验(详情请参见)

您是否尝试将
@manytone(cascade=CascadeType.ALL)
添加到子实体中?是的,但没有luckHey Tom,谢谢您的回答。我明白了。问题是我正在通过JSON将完整的POJO发送给控制器。POJO有父母和孩子。因此,最终我必须在session.save(parent)之前再次设置子级或父级。可以避免吗?我不确定我是否正确理解了您的场景,因为您是通过JSON传输POJO的,您不需要在取回POJO后(保存之前)将其合并吗?
child1.setParentid(parent);
public void addChild(Child child) {
    childCollection.add(child);
    child.setParentId(this);
}
public void setParent(Parent parent) {
    parent.getChildCollection().add(this);
    this.setParentId(parent)
}