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.

@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:

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.