JPA, Hibernate, and Data· 40 min

JPA Entities and Relationships

Map entities and relationships without creating accidental coupling or inefficient queries.

Java interview lesson
Question 22 · Not reviewed

Data · JPA mapping

Can you explain this clearly in an interview?

Use the strong answer as your reference, explain it aloud in your own words, then choose how soon you want to review it again.

Interview prompt

JPA Entities and Relationships

Explain it aloud in your own words

Strong answer

A JPA entity is a persistent identity managed by a persistence context, not just a row-shaped DTO. Map relationships from the side that owns the foreign key, default to lazy associations, keep bidirectional links consistent through helper methods, and give the entity a stable notion of identity. Relationship choices decide which SQL runs later, so model them from real access patterns rather than mirroring every table join.

Key points

  • The owning side (usually @ManyToOne or the side without mappedBy) controls the foreign-key column.
  • @ManyToOne and @OneToOne are EAGER by default; set fetch = LAZY explicitly.
  • equals and hashCode must not depend on a generated id that is null before persist, or on lazy associations.
  • Avoid @ManyToMany when the join has its own data; promote it to an explicit join entity.

Interviewer looks for

Explain owning versus inverse sides, why defaults like EAGER @ManyToOne hurt, and how you keep both sides of a bidirectional relationship in sync in memory.

Java example

1@Entity
2@Table(name = "orders")
3class Order {
4  @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
5  private Long id;
6
7  @ManyToOne(fetch = FetchType.LAZY, optional = false)
8  @JoinColumn(name = "customer_id")
9  private Customer customer;
10
11  @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
12  private List<OrderLine> lines = new ArrayList<>();
13
14  void addLine(OrderLine line) {
15    lines.add(line);
16    line.setOrder(this); // keep both sides consistent
17  }
18}

Topic interview questions

Revise this topic like an interviewer

These questions are tied to this lesson. Read each question aloud, then compare your explanation with the strong answer.

5 questions
Q1Basic

What is the difference between the owning side and the inverse side of a JPA relationship?

Strong answer

The owning side holds the foreign key mapping and is the side JPA reads when it writes the association to the database. The inverse side declares mappedBy and is ignored for persistence, so changing only the inverse collection does not update the foreign key.

Q2Intermediate

Why should @ManyToOne usually be marked LAZY?

Strong answer

JPA makes to-one associations EAGER by default, so every query that loads the child also loads the parent, often through extra selects or wide joins. LAZY lets each use case fetch the parent only when it needs it, typically with an explicit fetch join or entity graph.

Q3Advanced

How should equals and hashCode be implemented for an entity?

Strong answer

Base them on a stable business key or an id assigned before persistence, never on mutable fields or lazy associations. If a database-generated id is used, equality must treat transient entities carefully, otherwise an entity can change hash bucket after persist and get lost in a HashSet.

Q4Intermediate

When would you replace @ManyToMany with an explicit join entity?

Strong answer

As soon as the relationship needs its own attributes such as role, quantity, or created time, or needs its own lifecycle and queries. A join entity with two @ManyToOne links is easier to query, audit, and evolve than a hidden join table.

Q5Intermediate

What do cascade and orphanRemoval actually do?

Strong answer

cascade propagates entity-manager operations such as persist or remove from parent to children. orphanRemoval deletes a child row when it is removed from the parent's collection. Use them for true aggregate ownership, not for shared references like a Customer used by many orders.

How well do you know this?

Your review choice is saved locally and synced to your learner profile when signed in.