Spring Boot Entity Relationships

Real data connects. A customer places orders, a student joins courses, and a person holds a passport. Entity relationships describe these connections inside Java classes, and JPA translates them into foreign keys and join tables in the database.

Spring Data JPA supports four relationship types. Choosing the right type shapes the tables, the queries, and the speed of the application.

Three Everyday Pictures

Familiar situations explain each type without technical words.

  • One person holds one passport, and each passport belongs to one person. This is one-to-one.
  • One customer places many orders, and each order belongs to one customer. This is one-to-many from the customer side and many-to-one from the order side.
  • Many students join many courses, and each course enrolls many students. This is many-to-many.
 One-to-One          One-to-Many              Many-to-Many

 Person --- Passport   Customer --+-- Order 1   Student A --+-- Course X
                                  +-- Order 2             +-- Course Y
                                  +-- Order 3   Student B --+-- Course X

Foreign Keys in the Database

A foreign key is a column that stores the id of a row in another table. The "many" side of a relationship holds the key. An orders table carries a customer_id column, and each value points to one customer row.

 customers              orders
 +----+-------+         +----+-------+-------------+
 | id | name  |         | id | total | customer_id |
 +----+-------+         +----+-------+-------------+
 | 1  | Anna  | <------ | 10 | 49.00 | 1           |
 | 2  | Ravi  | <------ | 11 | 15.00 | 2           |
 +----+-------+         | 12 | 32.50 | 1           |
                        +----+-------+-------------+

Many-to-One and One-to-Many

The most common pair links an order to its customer.

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    private List<Order> orders = new ArrayList<>();
}

@Entity
@Table(name = "orders")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private double total;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_id")
    private Customer customer;
}

The order class owns the foreign key through @JoinColumn. The customer class uses mappedBy to say that the order side controls the link.

One-to-One

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "passport_id")
    private Passport passport;
}

The person table stores passport_id. Saving a person with CascadeType.ALL saves the passport in the same step.

Many-to-Many

Many-to-many needs a third table called a join table. It holds one row per connection.

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToMany
    @JoinTable(
        name = "student_course",
        joinColumns = @JoinColumn(name = "student_id"),
        inverseJoinColumns = @JoinColumn(name = "course_id"))
    private Set<Course> courses = new HashSet<>();
}

@Entity
public class Course {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToMany(mappedBy = "courses")
    private Set<Student> students = new HashSet<>();
}
 student            student_course          course
 +----+------+      +------------+-----------+      +----+--------+
 | 1  | Mia  | <--- | student_id | course_id | ---> | 7  | Java   |
 | 2  | Leo  |      | 1          | 7         |      | 8  | Spring |
 +----+------+      | 1          | 8         |      +----+--------+
                    | 2          | 7         |
                    +------------+-----------+

Fetch Types

Fetch type decides when related data loads.

TypeBehaviorDefault For
LAZYLoads related data when code asks for itOneToMany, ManyToMany
EAGERLoads related data immediately with the parentManyToOne, OneToOne

Lazy loading saves memory and time. Mark ManyToOne links as LAZY to avoid loading unneeded rows.

Cascade Types

Cascade passes an action from a parent to its children. CascadeType.PERSIST saves children with the parent. CascadeType.REMOVE deletes children with the parent. CascadeType.ALL covers every action. Apply cascade only where the child cannot live without the parent, such as order items inside an order.

Avoiding Endless JSON Loops

A customer lists orders, and each order points back to the customer. Converting this loop to JSON runs forever and ends in an error. Break the loop with @JsonIgnore on one side, or return simple DTO classes from the controller.

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id")
@JsonIgnore
private Customer customer;

Choosing the Owning Side

Every relationship has an owning side, the entity whose table stores the foreign key. JPA writes the key only when the owning side changes. A developer who updates the inverse side alone sees no change in the database. Keep both sides in sync with helper methods, such as addOrder on the customer class, which sets the link in both directions. Such methods prevent half-connected objects and confusing results.

Best Practices

  • Prefer LAZY loading and fetch related data only when required.
  • Keep one side as the owner and use mappedBy on the other.
  • Use Set instead of List for many-to-many collections.
  • Return DTOs from controllers to hide internal structure.
  • Test queries with SQL logging turned on to catch hidden extra queries.

Correct relationships keep data consistent and queries tidy. Clear mappings let the database enforce the connections that the business already understands.