Stephan
Stephan

Reputation: 43013

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 ?

Upvotes: 2

Views: 3786

Answers (3)

imotai
imotai

Reputation: 2086

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;

   (...)
}

Upvotes: 2

rompetroll
rompetroll

Reputation: 4799

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;

Upvotes: 2

Thomas
Thomas

Reputation: 88707

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.

Upvotes: 3

Related Questions