簡體   English   中英

休眠-一對多關系-外鍵始終為“空”

[英]Hibernate - One to many relation - foreign key always “null”

我有兩個非常簡單的對象,並且一個對象應在一組“一對多”關系中包含另一個對象。 對象已正確插入數據庫中,但“子項”表中的外鍵始終為“ 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();
}

有人可以解釋一下為什么會這樣嗎?

這很簡單:您永遠不會在Children初始化testObj字段(應將其命名為Child,BTW)。 Children.testObj是關聯的所有者,並且是映射到聯接列的字段,因此,如果為null,則聯接列將為null。

我有一個類似的問題,我通過致電業主一方的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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM