【问题标题】:Two references in the same entity to another entity同一实体中对另一个实体的两次引用
【发布时间】:2014-03-15 23:30:49
【问题描述】:

我有实体User,这个实体在另一个实体Product 中使用了两次。我使用休眠和创建表之间的外键。还有两个外键 - 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

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

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

    如果您希望 createdBymodifiedBy 关联是双向的,您需要在 User 中使用两个字段:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-19
      • 2011-07-18
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多