简体   繁体   中英

JPA - OneToMany, ManyToOne, OneToOne problem

Given the following two entities :

class Parent {
       @OneToMany(cascade=CascadeType.ALL)
       private Set<Child> children;

       (...)
}


class Child {
       @ManyToOne
       private Parent parent;

       (...)
}

I would like two tables in the database. One table for the parents and the other one for the children. But Hibernate creates three tables: one for the parents, one for the children and one for joining them (table with two fields).

Even if I put @OneToOne on the parent attribute in Child class, I still get the same result.

What am I missing ?

Add the mappedBy property to the @OneToMany in the Parent class. This makes the Child be the owning side.

In Child add the @JoinColumn annotation to the parent field in order to declare the foreign key column name in the child table.

From the JavaDoc on @OneToMany#mappedBy :

The field that owns the relationship. Required unless the relationship is unidirectional.

Unidirectional relations need a join table, but in your case it's bidirectional, thus it's required.

The mappedBy="parent" attribute in annotation is missing for building the bidirectional association.

class Parent {
   @OneToMany(mappedBy="parent",cascade=CascadeType.ALL)
   private Set<Child> children;

   (...)
}

class Child {
   @ManyToOne
   private Parent parent;

   (...)
}

given your foreign key column in the children table is called "parent_id", try

@OneToMany(mappedBy="parent")
private Set<Child> children;

and

@ManyToOne
@JoinColumn(name="parent_id")
private Parent parent;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM