Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

One-to-Many Mapping in Hibernate

Introduction

One-to-Many mapping is a crucial concept in Hibernate that allows you to establish a relationship between two entities where one entity can be associated with multiple instances of another entity. This kind of mapping is commonly found in various database scenarios, such as a single author having multiple books or a single department containing multiple employees.

Understanding One-to-Many Mapping

In a one-to-many mapping, one entity (parent) can have multiple instances of another entity (child). In Hibernate, this is typically represented using a collection in the parent class, such as a List or Set. The child class contains a foreign key that references the parent class.

For example, consider a relationship between a Library and Books. A library can have many books, but each book belongs to one library.

Entity Classes

Library Class

public class Library {

  @Id

  @GeneratedValue(strategy = GenerationType.IDENTITY)

  private Long id;

  private String name;

  @OneToMany(mappedBy = "library", cascade = CascadeType.ALL)

  private List books;

}

Book Class

public class Book {

  @Id

  @GeneratedValue(strategy = GenerationType.IDENTITY)

  private Long id;

  private String title;

  @ManyToOne

  @JoinColumn(name = "library_id")

  private Library library;

}

Mapping Annotations Explained

In the above classes, we used several important annotations:

  • @Entity: Marks the class as a Hibernate entity.
  • @Id: Indicates the primary key of the entity.
  • @GeneratedValue: Specifies how the primary key should be generated.
  • @OneToMany: Defines a one-to-many relationship.
  • @ManyToOne: Defines a many-to-one relationship.
  • @JoinColumn: Specifies the foreign key column in the child entity.

Creating and Persisting Data

To create and persist data in a one-to-many relationship, we can do the following:

Library library = new Library();

library.setName("Central Library");

Book book1 = new Book();

book1.setTitle("Hibernate Basics");

book1.setLibrary(library);

Book book2 = new Book();

book2.setTitle("Java Programming");

book2.setLibrary(library);

library.setBooks(Arrays.asList(book1, book2));

session.save(library);

Querying Data

To retrieve the data, you can use HQL or Criteria API. For example, to get all books in a specific library:

String hql = "FROM Book b WHERE b.library.id = :libraryId";

Query query = session.createQuery(hql);

query.setParameter("libraryId", libraryId);

List books = query.list();

Conclusion

One-to-many mapping is a powerful feature in Hibernate that allows developers to manage complex relationships between entities efficiently. By understanding how to create entity classes, utilize annotations, and persist and query data, you can effectively implement one-to-many relationships in your applications.