Many-to-One Hibernate Mapping with Example

A Many-to-One association mapping is the reverse of One-to-Many association mapping. For example, many (customers) are associated with one (vendor). In Hibernate, Many-to-One association mapping is applied from child class object to parent class object. It is an N to 1 relationship.

For example, there are many customers of a single vendor; it is just the reverse of one-to-many association mapping. Here, we need to take a collection property like Set, Map, Bag, and List in the Customer.java class.

Now, we are going to create an example, in which there are two persistent classes, i.e., Customers and Vendor. Here, we are taking a unidirectional mapping, so we need to define @ManyToOne and @JoinColumn annotations in the Customer class.

Following are the steps to create the example:

  1. Create all persistent classes

In this step, we are going to develop persistent classes, i.e., Vendor.java and Customer.java.

Vendor.java

Customer.java

  • Create the configuration file

In this step, we are going to create the configuration class (hibernate.cfg.xml) which contains the information of persistent class and the database.

hibernate.cfg.xml

  • Create the main class that stores the object of  the persistent class

In this step, we are going to create a class which consists of main() method, and stores the objects of persistent classes.

App.java

  • Output
Many-to-One Hibernate Mapping
  • Table

Custo table

Custo table Many-to-One Hibernate Mapping

Vend table

Vend table Many-to-One Hibernate Mapping

Pin It on Pinterest

Share This