Here's an excerpt of the official Hibernate tutorial
First, keep in mind that Hibernate does not affect normal Java semantics. How did we create a link between a Person and an Event in the unidirectional example? You add an instance of Event to the collection of event references, of an instance of Person. If you want to make this link bi-directional, you have to do the same on the other side by adding a Person reference to the collection in an Event. This process of "setting the link on both sides" is absolutely necessary with bi-directional links.
Many developers program defensively and create link management methods to correctly set both sides (for example, in Person):
protected Set getEvents() {
return events;
}
protected void setEvents(Set events) {
this.events = events;
}
public void addToEvent(Event event) {
this.getEvents().add(event);
event.getParticipants().add(this);
}
public void removeFromEvent(Event event) {
this.getEvents().remove(event);
event.getParticipants().remove(this);
}
What does the word "absolutely" mean in this case? :
In other words, what would happen if my "adding" method is:
public void addToEvent(Event event) {
this.getEvents().add(event);
//event.getParticipants().add(this); without this line
}
It means that the in-memory copies of both data structures aren't automatically updated when you add one side of a relationship, so that while your code is using the Java proxies for the database rows, you might add an event to a participant's event list, but the event wouldn't show the participant, and any code that was (reasonably) relying on the two being in sync would fail. This is an obnoxious pitfall in JPA, but it isn't Hibernate-specific and doesn't appear to be going away any time soon.