gpt4 book ai didi

java - 同一实体中对另一个实体的两次引用

转载 作者:行者123 更新时间:2023-12-02 06:04:05 27 4
gpt4 key购买 nike

我有实体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

最佳答案

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

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

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

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

关于java - 同一实体中对另一个实体的两次引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22431073/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com