同一实体中的两个引用到另一个实体

时间:2014-03-15 23:30:49

标签: java hibernate

我有实体User,此实体在另一个实体Product中使用了两次。我使用hibernate和表之间的外键创建。还有两个外键 - 用于create_by和modified_by。

类用户

class User {

    private Set<Product> products = new HashSet<Product>(0);

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
    public Set<ProductgetProducts{
        return this.products
    }

    public void setProducts(Set<Product> products) {
        this.products = products
    }
}

类产品

class Product {
    private User createdBy;
    private User modifiedBy;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinColumn(name = "modified_by", nullable = false)
    public User getModifiedBy() {
        return modifiedBy;
    }

    public void setModifiedBy(User createdBy) {
        this.modifiedBy= modifiedBy;
    }

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinColumn(name = "created_by", nullable = false)
    public User getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(User createdBy) {
        this.createdBy = createdBy;
    }
}

它抛出了我的异常,我不知道如何解决它。

Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: Product.user in User.products

1 个答案:

答案 0 :(得分:2)

mappedBy = "user"表示:我是双向关联的反面,其所有者方是目标实体(即产品)中的字段user。 Product中没有user字段。所以它没有意义。

如果您希望createdBy广告modifiedBy关联是双向的,则需要在用户中添加两个字段:

@OneToMany(mappedBy = "createdBy")
private Set<Product> createdProducts;

@OneToMany(mappedBy = "modifiedBy")
private Set<Product> modifiedProducts;