mappedBy引用未知的目标实体属性

boy*_*715 64 java orm hibernate hibernate-annotations

我在注释对象中设置一对多关系时遇到问题.

我有以下内容:

@MappedSuperclass
public abstract class MappedModel
{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id",nullable=false,unique=true)
    private Long mId;
Run Code Online (Sandbox Code Playgroud)

那么这个

@Entity
@Table(name="customer")
public class Customer extends MappedModel implements Serializable
{

    /**
   * 
   */
  private static final long serialVersionUID = -2543425088717298236L;


  /** The collection of stores. */
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private Collection<Store> stores;
Run Code Online (Sandbox Code Playgroud)

还有这个

@Entity
@Table(name="store")
public class Store extends MappedModel implements Serializable
{

    /**
   * 
   */
  private static final long serialVersionUID = -9017650847571487336L;

  /** many stores have a single customer **/
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn (name="customer_id",referencedColumnName="id",nullable=false,unique=true)
  private Customer mCustomer;
Run Code Online (Sandbox Code Playgroud)

我在这做什么不正确

Pas*_*ent 119

mappedBy属性被引用customer,而属性是mCustomer,因此,该错误消息.所以要么将映射更改为:

/** The collection of stores. */
@OneToMany(mappedBy = "mCustomer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<Store> stores;
Run Code Online (Sandbox Code Playgroud)

或者将实体属性更改为customer(我会这样做).

mappedBy引用指示"在我收集的东西上查找名为'customer'的bean属性以查找配置."


小智 16

我知道@Pascal Thivent的回答已经解决了这个问题。我想在他对可能浏览此线程的其他人的回答中添加更多内容。

如果你和我一样,在刚开始学习的时候,对使用@OneToMany带有 ' mappedBy' 属性的注解的概念感到头疼,这也意味着持有@ManyToOne带有@JoinColumn'的注解的另一边是这个双向的“所有者”关系。

此外,mappedBy将类变量的实例名称mCustomer在本例中)作为输入,而不是类类型(例如:客户)或实体名称(例如:客户)。

奖励:另外,查看注释的orphanRemoval属性@OneToMany。如果设置为 true,那么如果在双向关系中删除了父级,Hibernate 会自动删除它的子级。