6

我有两个非常简单的对象,一个对象应该在集合中以“一对多”关系包含另一个对象。对象被正确插入到数据库中,但“children”表中的外键始终为“null”。

我不知道为什么:

这是测试对象,它把孩子放在它的集合中:

@Entity
@Table(name="test")
public class TestObj {

    public TestObj(){}

    private Long id;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    private Set<Children> children = new HashSet<Children>();

    @OneToMany(mappedBy = "testObj", cascade = CascadeType.ALL)
    public synchronized Set<Children> getChildren() {
        return children;
    }
    public synchronized void setChildren(Set<Children> children) {
        this.children = children;
    }
    public void addChildren(Children child){
        children.add(child);
    }
}

这是子对象,它拥有指向“TestObj”的反向链接:

@Entity
@Table(name = "children")
public class Children {

    public Children(){}

    private Long id;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }

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

    private TestObj testObj;

    @ManyToOne
    @JoinColumn
    public TestObj getTestObj() {
        return testObj;
    }

    public void setTestObj(TestObj testObj) {
        this.testObj = testObj;
    }
}

我使用以下代码保留这些对象:

EntityManagerFactory entityManagerFactory = HibernateEntityMangerSingelton.getEntityManagerFactory();
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();


TestObj user = new TestObj();

Children child = new Children();
user.addChildren(child);
try {

    entityManager.persist(user);

    entityManager.getTransaction().commit();

} catch (Exception e) {
    System.out.println(e);
}finally{
    entityManager.close();
}

有人可以解释一下为什么会这样吗?

4

2 回答 2

8

这很简单:您永远不会初始化testObj字段Children(应该命名为 Child,BTW)。Children.testObj是关联的所有者,并且是映射到联接列的字段,因此如果为空,则联接列将为空。

于 2013-05-31T20:45:22.317 回答
4

我有一个类似的问题,我通过调用所有者方的 setter 来解决。应该像这样更改设置并将子项添加到 TestObj 的 2 个方法,以便在所有者端初始化 TestObj:

public synchronized void setChildren(Set<Children> children) 

{



this.children = children;


for(Children child : children)
    {
    // initializing the TestObj instance in Children class (Owner side) so that it is not a null and PK can be created
            child.setTestObj(this);
    }
    }

第二种方法:

public void addChildren(Children child)
{
    children.add(child);
//Intializing the TestObj instance at the owner side
    child.setTestObj(this);
}
于 2014-09-12T08:39:36.520 回答