2016-10-03 68 views
1

我有表與循環引用如何Hibernate註解循環引用

-----------------|     |------------------ 
    product  |     | product_detail 
-----------------|     |------------------ 
product_id <pk> |     | detail_id <pk> 
    ...   | <-----------------| container_id <fk> 
       | <-----------------| product_id <fk> 
       |     | ... 

我想知道怎麼辦物業註解

怎麼辦@OneToMany註釋

Class Product 
@OneToMany ??? 
public List<Detail> getDetails(); 

怎麼辦@ManyToOne註釋

Class Detail 

@ManyToOne ??? 
public Product getContainer(); 

@ManyToOne ??? 
public Product getProduct(); 

我以後要使用下面的代碼:

Product p1 = new Product(name2); 
    Product p2 = new Product(name1); 

    Detail d = new Detail(); 

    d.setProduct(p2); 

    p1.getDetails().add(d); 

    ... 

    Session.save(p1); 

則Hibernate插入到產品並插入到細節了。

我沒有找到創建註釋來實現它的方法。你能幫我嗎?

+0

https://zh.wikibooks.org/wiki/Java_Persistence/OneToMany#Example_of_a_OneToMany_relationship_and_inverse_ManyToOne_annotations –

+0

mappedBy(on @ @ OneToMany')使它成爲BIDIRECTIONAL關係。這就是所有需要的 –

+0

是的,這是我之前嘗試過的方式,但後來我得到超時超時錯誤。 @OneToMany(mappedBy =「container」)爲getDetails()列表和@ManyToOne @JoinColumn(name =「container_id」)爲getContainer() – axiorema

回答

1

在你的情況你的代碼應該如下:

Class Product 
@OneToMany(mappedBy = "product") 
public List<Detail> getDetails(); 

具體交易類,你應該能夠使用@ManyToOne註解是。所以:

Class Detail 
@ManyToOne 
public Product getContainer(); 

@ManyToOne 
public Product getProduct(); 

這背後的原因是,在你的@OneToMany你在這在詳細類字段指的是此產品的參數的mappedBy注意。只要您遵守標準的命名約定,您就不需要@ManyToOne批註中的任何額外信息。

+0

與此解決方案詳細信息objet沒有插入db中,只有產品 – axiorema

+0

嗨axiorema,請看看https://vladmihalcea.com/2015/03/05/a-beginners-guide-to-jpa-and-hibernate-cascade-types/,然後查看一對多部分。將cascade = CascadeType.PERSIST添加到@OneToMany註釋中應該注意將子項與父項一起保存。 –

0

我嘗試了使用mappedBy發佈的解決方案,但是當我運行示例代碼時,只有產品插入到數據庫中。

的唯一途徑,我發現它工作正常使用具有一對多端所有者註釋:

Class Detail 
    @ManyToOne(cascade={CascadeType.ALL}) 
    @JoinColumn(name="container_id") 
    public Product getContainer() { 

    @ManyToOne 
    @JoinColumn(name="product_id") 
    public Product getProduct() { 

Class Product 
    @OneToMany(cascade={CascadeType.ALL}) 
    @JoinColumn(name="container_id") 
    public Set<Detail> getDetails() 

這是示例代碼:

Product p1 = new Product("the container"); 
    Product p2 = new Product("the product"); 

    Detail d = new Detail(); 

    d.setProduct(p2); 

    p1.getDetails().add(d); 

    session.save(p2); 
    session.save(p1); 

在這種情況下,德兩種產品被插入和細節也被插入。

但也有不方便的,因爲如果我不希望接收:

SQLIntegrityConstraintViolationException: Column 'container_id' cannot be null 

我必須改變德表詳細信息和設置的外鍵「CONTAINER_ID」爲NULL,這是不符合模型

CHANGE COLUMN `container_id` `container_id` INT(11) NULL 

其中一個細節必須始終有一個容器產品。

任何人都可以對這個問題有所瞭解嗎?