如何使用循环引用来休眠注释

时间:2016-10-03 11:18:01

标签: java hibernate hibernate-annotations

我有两个带循环引用的表

-----------------|                   |------------------
  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);

然后暂停insert into productinsert into detail

我找不到创建注释以使其工作的方法。你能帮帮我吗?

2 个答案:

答案 0 :(得分:1)

在您的情况下,您的代码应如下所示:

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

对于Detail类,您应该可以按原样使用@ManyToOne注释。所以:

Class Detail
@ManyToOne
public Product getContainer();

@ManyToOne
public Product getProduct();

这背后的原因是在你的@OneToMany中你注意到在mappedBy参数中,Detail类中的哪个字段指的是 this Product 。只要您遵守标准命名约定,就不需要@ManyToOne注释中的任何额外信息。

答案 1 :(得分:0)

我尝试使用mappedBy发布的解决方案,但是当我运行示例代码时,只在db上插入产品。

我发现它工作正常的唯一方法是使用OneToMany方所有者的注释:

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

我必须更改de table detail并设置外键&#39; container_id&#39;为NULL,这与模型不一致

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

其中详细信息必须始终包含容器产品。

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