Spring JPA Cardinality

Spring JPA Cardinality

Database relation using JPA Cardinality

Table of contents

No heading

No headings in the article.

Spring JPA Cardinality refers to the relationship between two entities regarding how many instances of one entity can be associated with a single instance of another entity. Here's a breakdown with code examples:


  • One-to-One (OneToOne): One entity instance can be associated with at most one instance of another entity, and vice versa.
@Entity
public class User {

  @Id
  private Long id;

  @OneToOne(mappedBy = "user")
  private Account account;

  // Getters and Setters
}

@Entity
public class Account {

  @Id
  private Long id;

  @OneToOne
  @JoinColumn(name = "user_id") // Optional for defining foreign key column
  private User user;

  // Getters and Setters
}

  • One-to-Many (OneToMany): One entity instance can be associated with many instances of another entity, but a single instance of the other entity can only be associated with one instance of the first entity.

      @Entity
      public class Instructor {
    
        @Id
        private Long id;
    
        @OneToMany(mappedBy = "instructor")
        private List<Course> courses;
    
        // Getters and Setters
      }
    
      @Entity
      public class Course {
    
        @Id
        private Long id;
    
        @ManyToOne
        @JoinColumn(name = "instructor_id") // Optional for defining foreign key column
        private Instructor instructor;
    
        // Getters and Setters
      }
    

  • Many-to-One (ManyToOne): Similar to One-to-Many, but reversed. Many entity instances can be associated with one instance of another entity.
@Entity
public class Order {

  @Id
  private Long id;

  @ManyToOne
  @JoinColumn(name = "customer_id") // Optional for defining foreign key column
  private Customer customer;

  // Getters and Setters
}

@Entity
public class Customer {

  @Id
  private Long id;

  @OneToMany(mappedBy = "customer")
  private List<Order> orders;

  // Getters and Setters
}

  • Many-to-Many (ManyToMany): Many entity instances can be associated with many instances of another entity. This usually involves a separate join table to manage the relationships.

      @Entity
      public class Student {
    
        @Id
        private Long id;
    
        @ManyToMany(mappedBy = "students")
        private List<Course> courses;
    
        // Getters and Setters
      }
    
      @Entity
      public class Course {
    
        @Id
        private Long id;
    
        @ManyToMany
        @JoinTable(name = "student_course",
            joinColumns = @JoinColumn(name = "course_id"),
            inverseJoinColumns = @JoinColumn(name = "student_id")) // Define join table details
        private List<Student> students;
    
        // Getters and Setters
      }