Search code examples
javahibernatehibernate-mapping

Hibernate - One to Many Mapping of Set - Annotations


Newbie to Hibernate here. I'm building a simple app to play around with Hibernate and I'm getting the hang of most of the annotations but the mappings are really confusing me.

I have a Person class and I have a Note's class. A person can have many notes associated with them but a single note will only ever correspond to a specific person.

I'm trying to set it up so that the note table has a column called person_id such that I won't need an extra person_note table in the database for the associations.

How would I go about setting up the annotations such that an extra table is not created in the database and I can associate multiple notes to a single person via an extra column in the note's table?

I've tried a few options after searching on Google such as using annotations like this but with no luck:

@JoinColumn(name="id_person", nullable=false)

Person Class

@Entity
@Table(name = "person")
public class Person {

    @OneToMany()
    private Set<Note> notes;

    public Set<Note> getNotes() {
        return notes;
    }

    public void setNotes(Set<Note> notes) {
        this.notes = notes;
    }

    ...

}

Note Class

@Entity
@Table (name = "note")
public class Note {

    @ManyToOne
    private Person person;

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

   ...

}

Any help would be appreciated. Thank you.


Final Working Solution

For the benefit of anyone looking in the future, I now don't have a separate table for mapping note objects to people objects. The final code (with extra lines removed) now looks like this:

Person Class

@Entity
@Table(name = "person")
public class Person {

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "person", cascade = CascadeType.ALL)
    private Set<Note> notes;

    ...

}

Note Class

@Entity
@Table (name = "note")
public class Note {

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "id_person", nullable = false)
    private Person person;

   ...

}

Misc Points

  • I had to add cascade = CascadeType.ALL in the Person class to ensure that when I saved a Person object that all the Note objects inside were saved.
  • I combined the code from chsdk and Saif. Thank you to both of you.

Solution

  • In your mapping annotations you should map the entities with a mappedBy property in the @OneToMany annotation and specify a joinColumn under the @ManyToOne annotation using the @JoinColumn annotation, Change your code like this:

    Person class:

    @OneToMany(mappedBy = "person") // "person" here refers to the person property in the notes class
    private Set<Note> notes;
    

    Notes class:

    @ManyToOne
    @JoinColumn(name = "id_person", nullable = false)
    private Person person;
    

    Take a look at Hibernate Collection mapping for further information.