2016-10-03 63 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 

其中一个细节必须始终有一个容器产品。

任何人都可以对这个问题有所了解吗?