Search code examples
javahibernatejpapersistenceone-to-many

Hibernate OneToMany relationship sets foreign key to null when inserting entity


I have two entities: Person and Event. The idea is that a Person is the owner of several events and an event can be owned by only one Person.

Snippet of Person entity:

@OneToMany(fetch = FetchType.EAGER,cascade=CascadeType.ALL,mappedBy="person")
@JsonIgnore
private List<Event> event;

Snippet of Event entity:

@ManyToOne(fetch=FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH})
@JsonIgnore
private Person person;

When I try inserting a Person and add some events to it afterwards in the database the foreign key in the Event table is always null. This means that I cannot keep track of the "owner" of the event (which is what I aim to do).

Moreover, if I wanted to use a @JoinTable annotation instead to keep track of the owner how should I do that?

Any suggestion is appreciated.


Solution

  • Probably you are not wiring the entities correctly. The following pseodo code will show you how to wire the entities:

    Person person = new Person();
    Event event1 = new Event();
    Event event2 = new Event();
    
    person.getEvents().add(event1);
    person.getEvents().add(event2);
    
    event1.setPerson(person);
    event2.setPerson(person);
    
    // Start transaction here 
    entityManager.persist(person); // this should save also events because of cascade attribute
    // commit transaction
    

    Moreover, if I wanted to use a @JoinTable annotation instead to keep track of the owner how should I do that?

    In your case, you don't need it because you have a bidirectional relationship. That makes sense only if you have an unidirectional @OneToMany relationship from Person to Event.