Explore Topics

Hibernate CRUD & Mappings

Hibernate is a powerful Object-Relational Mapping (ORM) framework that simplifies database interactions by mapping Java objects to database tables. In this section, we’ll cover the basics of Hibernate CRUD operations (Create, Read, Update, Delete) and how to handle different types of entity mappings: One-to-One, One-to-Many, and Many-to-Many.

Hibernate CRUD Operations

Create: To insert a new record into the database, you can use session.save() or session.persist(). These methods add a new entity into the database.

Read: You can retrieve an entity using session.get() or session.load().

Update: To update an existing entity, Hibernate uses session.update() or session.merge().

Delete: To delete an entity, use session.delete()

Hibernate Entity Mappings

One-to-One Mapping: In a one-to-one relationship, one entity is associated with exactly one instance of another entity. For example, a person has one passport.

Mapping Example:

One-to-Many Mapping: A one-to-many relationship means one entity is associated with multiple instances of another entity. For example, one department has many employees.

Mapping Example:

Many-to-Many Mapping: A many-to-many relationship means that multiple instances of one entity are related to multiple instances of another entity. For example, students and courses.

Mapping Example: