orshachar
orshachar

Reputation: 5037

javax.persistence one to many - how does it work?

Say that I have 2 Entites of User and Message. User has a field called "messages" that has a list of messages and is annotated with "@manyToOne" and Message has a field called "owner" like the following:

User:

@Entity
Class User{
...
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
private List messages;
...

}


Message:

@Entity
Class Message{
...
@ManyToOne(fetch = FetchType.LAZY)
private User owner;
...
}

My question - when adding a new message and setting the owner to be certain user, does the persistence knows to add another element to the User Object's "messages" list?

In other words: when creating a message and setting the "owner" - does the appropriate User "messages" list automatically increased by one?

Upvotes: 2

Views: 2474

Answers (1)

Affe
Affe

Reputation: 47994

No, to write strictly correct code you need to maintain both sides or your bidirectional relationships in memory. It's not going to automagically add an element to a collection somewhere else as a result of setting a property.

The new message will be there if you refresh your User from the database or otherwise reload it, but that still isn't entirely safe in systems with L2 caching. You should always maintain both sides of the relationship for maximum portability.

Something like this is not that uncommon to see on your User entity:

public Message addMessage(Message message) {
  //null checks and duplicate checks omitted
  messages.add(message);
  message.setOwner(this);
  return message;
}

Upvotes: 4

Related Questions