Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java One-to-many Relationship Example

In this tutorial, we will demonstrate a simple one-to-many relationship example in Java using a school with students. A school can have multiple students, but each student belongs to only one school. We will model this relationship using two classes: School and Student.

  • Define the Student class:
public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + '}';
    }
}
  • Define the School class:
import java.util.ArrayList;
import java.util.List;

public class School {
    private String name;
    private List<Student> students;

    public School(String name) {
        this.name = name;
        this.students = new ArrayList<>();
    }

    public String getName() {
        return name;
    }

    public void addStudent(Student student) {
        this.students.add(student);
    }

    public List<Student> getStudents() {
        return students;
    }

    @Override
    public String toString() {
        return "School{name='" + name + "', students=" + students + '}';
    }
}
  • Create a simple example to demonstrate the one-to-many relationship:
public class Main {
    public static void main(String[] args) {
        School school = new School("ABC School");

        Student student1 = new Student("John Doe", 15);
        Student student2 = new Student("Jane Smith", 16);
        Student student3 = new Student("Michael Brown", 17);

        school.addStudent(student1);
        school.addStudent(student2);
        school.addStudent(student3);

        System.out.println(school);
    }
}

Output:

School{name='ABC School', students=[Student{name='John Doe', age=15}, Student{name='Jane Smith', age=16}, Student{name='Michael Brown', age=17}]}

In this example, we created a School class and a Student class to model a one-to-many relationship between a school and its students. A school can have multiple students, but each student belongs to only one school. This relationship is demonstrated by the students list in the School class, which stores references to the Student objects.

  1. Hibernate One-to-Many Mapping in Java:

    • In Hibernate, a one-to-many relationship is established using annotations like @OneToMany and @ManyToOne.
    @Entity
    public class Parent {
        @OneToMany(mappedBy = "parent")
        private List<Child> children;
        // other fields and methods
    }
    
    @Entity
    public class Child {
        @ManyToOne
        @JoinColumn(name = "parent_id")
        private Parent parent;
        // other fields and methods
    }
    
  2. Spring Data JPA One-to-Many Example:

    • Spring Data JPA simplifies the data access layer. Here's an example of a one-to-many relationship using Spring Data JPA.
    @Entity
    public class Parent {
        @OneToMany(mappedBy = "parent")
        private List<Child> children;
        // other fields and methods
    }
    
    @Entity
    public class Child {
        @ManyToOne
        @JoinColumn(name = "parent_id")
        private Parent parent;
        // other fields and methods
    }
    
  3. Java Hibernate Bidirectional One-to-Many Mapping:

    • Bidirectional mapping involves both @OneToMany and @ManyToOne annotations in the related entities.
    @Entity
    public class Parent {
        @OneToMany(mappedBy = "parent")
        private List<Child> children;
        // other fields and methods
    }
    
    @Entity
    public class Child {
        @ManyToOne
        @JoinColumn(name = "parent_id")
        private Parent parent;
        // other fields and methods
    }
    
  4. Java JPA Unidirectional One-to-Many Relationship:

    • Unidirectional mapping involves only one side being aware of the relationship.
    @Entity
    public class Parent {
        @OneToMany
        @JoinColumn(name = "parent_id")
        private List<Child> children;
        // other fields and methods
    }
    
  5. Java Hibernate One-to-Many Annotation:

    • The @OneToMany annotation is used to define a one-to-many relationship in Hibernate.
    @Entity
    public class Parent {
        @OneToMany(mappedBy = "parent")
        private List<Child> children;
        // other fields and methods
    }
    
  6. OneToMany Mapping in Java Using Annotations:

    • Annotations like @OneToMany and @JoinColumn are used to map one-to-many relationships.
    @Entity
    public class Parent {
        @OneToMany(mappedBy = "parent")
        private List<Child> children;
        // other fields and methods
    }
    
  7. Java Hibernate mappedBy Attribute Explanation:

    • The mappedBy attribute in @OneToMany indicates the field in the child class that owns the relationship.
    @Entity
    public class Parent {
        @OneToMany(mappedBy = "parent")
        private List<Child> children;
        // other fields and methods
    }
    
  8. Java JPA CascadeType in One-to-Many Relationships:

    • The CascadeType defines how operations (like persist, remove) should cascade from parent to child entities.
    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<Child> children;
    
  9. Java Hibernate orphanRemoval in One-to-Many:

    • The orphanRemoval attribute removes child entities when they are removed from the collection.
    @OneToMany(mappedBy = "parent", orphanRemoval = true)
    private List<Child> children;
    
  10. Spring Boot JPA One-to-Many Relationship:

    • Spring Boot simplifies the setup of JPA relationships, making it easy to define one-to-many relationships.
    @Entity
    public class Parent {
        @OneToMany(mappedBy = "parent")
        private List<Child> children;
        // other fields and methods
    }
    
  11. Java JPA FetchType in One-to-Many Mapping:

    • The FetchType defines how the associated entities are loaded. LAZY loads them when needed, while EAGER loads them immediately.
    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    private List<Child> children;
    
  12. OneToMany Mapping with JoinTable in Java:

    • The @JoinTable annotation is used to map a many-to-many relationship using an intermediate table.
    @Entity
    public class Parent {
        @OneToMany
        @JoinTable(name = "parent_child",
            joinColumns = @JoinColumn(name = "parent_id"),
            inverseJoinColumns = @JoinColumn(name = "child_id"))
        private List<Child> children;
        // other fields and methods
    }
    
  13. Java Hibernate Lazy Loading in One-to-Many:

    • Lazy loading loads associated entities only when they are accessed, improving performance.
    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    private List<Child> children;