Relationships Between Entities
Object relationships should reflect data relationships
In a relational database, entities are often connected by foreign keys. In an object model, it is more convenient to work with the owner object itself rather than only its identifier. JPA lets you describe that relationship with annotations.
Many-to-one is a common case
@Entity
public class Order {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
}
Many orders can belong to one user, so from the Order side
this is a @ManyToOne relationship.
@JoinColumn specifies the foreign-key column that stores the relationship.
The main relationship types
@OneToOne— one object corresponds to one related object;@OneToMany— one object is related to a collection of many objects;@ManyToOne— many objects reference one object;@ManyToMany— collections of objects are related to collections on the other side.
A bidirectional relationship has an owning side
@OneToMany(mappedBy = "user")
private List<Order> orders = new ArrayList<>();
mappedBy = "user" shows that the foreign key is described by the user
field on the other side of the relationship. This matters: two references in Java do not mean two independent relationships in the database.
Keep both sides consistent in the object model.
If a relationship is bidirectional, it is useful to update both references consistently so that in-memory objects do not contradict each other.
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in