Sobes.tech
Senior

How to implement a one-to-many relationship?

sobes.tech AI

Answer from AI

In Java, a one-to-many relationship is usually implemented using collections in the class that represents the "one" object, and references to objects that represent the "many". For example, if we have a class Author and a class Book, where one author can have many books, then in the Author class there will be a field of type List<Book>.

Example:

import java.util.ArrayList;
import java.util.List;

class Book {
    private String title;

    public Book(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }
}

class Author {
    private String name;
    private List<Book> books = new ArrayList<>();

    public Author(String name) {
        this.name = name;
    }

    public void addBook(Book book) {
        books.add(book);
    }

    public List<Book> getBooks() {
        return books;
    }
}

In the context of ORM (for example, JPA/Hibernate), a one-to-many relationship is implemented using @OneToMany and @ManyToOne annotations to properly map the relationships in the database.