使用休眠保存父表时在外键中插入Null

时间:2018-11-12 13:41:22

标签: java hibernate

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

当我保存父表时,数据也将插入其子表中,但没有外键为NULL。

下面是我的代码: 父母:

public class Parent implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Size(max = 45)
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "parentid", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
private Collection<Child> childCollection;

public Parent() {
}

public Parent(Integer id) {
    this.id = id;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@XmlTransient
public Collection<Child> getChildCollection() {
    return childCollection;
}

public void setChildCollection(Collection<Child> childCollection) {
    this.childCollection = childCollection;
}

@Override
public int hashCode() {
    int hash = 0;
    hash += (id != null ? id.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Parent)) {
        return false;
    }
    Parent other = (Parent) object;
    if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "beans.Parent[ id=" + id + " ]";
}
}

孩子:

public class Child implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Size(max = 45)
@Column(name = "comments")
private String comments;
@JoinColumn(name = "parentid", referencedColumnName = "id", nullable = false)
@ManyToOne(fetch = FetchType.LAZY)
private Parent parentid;

public Child() {
}

public Child(Integer id) {
    this.id = id;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getComments() {
    return comments;
}

public void setComments(String comments) {
    this.comments = comments;
}

public Parent getParentid() {
    return parentid;
}

public void setParentid(Parent parentid) {
    this.parentid = parentid;
}

@Override
public int hashCode() {
    int hash = 0;
    hash += (id != null ? id.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Child)) {
        return false;
    }
    Child other = (Child) object;
    if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "beans.Child[ id=" + id + " ]";
} }

休眠服务:

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("*****");



} }

我找到了一种解决方法,如下所示,我将孩子反向映射到父母

child1.setParentid(parent);

但是我正在考虑是否可以避免这种情况。我希望可以通过其他方式不必将每个孩子都映射到其父母。

Kinldy的帮助,如果可以解释的话。

1 个答案:

答案 0 :(得分:2)

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

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

public void addChild(Child child) {
    childCollection.add(child);
    child.setParentId(this);
}

或/和反之亦然:

public void setParent(Parent parent) {
    parent.getChildCollection().add(this);
    this.setParentId(parent)
}

(代码中没有必要进行空检查等,但应该给出想法)

,因此使代码少了一些容易出错的地方(即忘记更新关系的另一面)。

似乎也有一个字节码增强功能,它将为您的实体的类文件添加类似的代码,但是我对它的工作效果没有任何经验(有关详细信息,请参见here