Hibernate Many to One Mapping Annotation Example

The Hibernate Many to One Mapping Annotation Example tutorial shows you how to use Hibernate Many-To-One Unidirectional mapping using annotation based configuration. The Many-To-One Unidirectional mapping said that one table has a foreign key column that referring the primary key of associated table.

We are taking an example of Student and ClassRoom relationship. This relationship said that a student registers one ClassRoom and one ClassRoom has many students.

Other interesting posts you may like

Create Database Table

We create two tables with these below scripts:

Noticed that STUDENT table contains a foreign key (here is class_room_id field) referring to a primary key (here is id field) of CLASS_ROOM table.

Create project directory structure

In this Hibernate Many to One Mapping Annotation Example tutorial, we will create java project with final directory structure.

Hibernate Many to One Mapping Annotation Example

Maven dependencies

We provide the required Hibernate and MySQL dependency in pom.xml like this:

Create Model classes

Model class Student and ClassRoom are simple POJO class. Here we are using class Student and ClassRoom with JPA annotations to map them to a database tables (these tables were created in above step).

Student Model class

ClassRoom Model class

Let’s dig deeper:

@ManyToOne annotation says that many Students refer to one ClassRoom and the attribute optional=false means this relationship becomes mandatory (no student row can be saved without a classRoom reference).

@JoinColumn annotation indicates that column CLASS_ROOM_ID in Student table will refer to primary key of the CLASS_ROOM table.

Create Hibernate configuration file

We need to provide for hiberate all stuffs like database dialect, driver class, url and account information to connect database. These stuffs is declared in file hibernate.cfg.xml like this:

This file is placed in src/main/resources folder.

Create Hibernate Utility class

For configuring hibernate on startup and managing session factory we create the HibernateUtil class like this:

Create program to demonstrate Hibernate Many to One Mapping Annotation Example

As discussed above, STUDENT table contains the foreign key referring to a primary key of CLASS_ROOM table. So that we have to persisted ClassRoom entity firstly then we set student’s classRoom property and persist student.

Run main class and we get the output like below:

That’s it on the Hibernate Many to One Mapping Annotation Example tutorial.

Download complete source code, please hit link below

ManyToOneMappingExample.zip (236 downloads)

Source code on Github https://github.com/javabycode/hibernate-many-to-one-mapping-annotation-example

Leave a Comment


Please share it if you found this useful
Hide Buttons