One-to-One Hibernate Mapping

In One-to-One association mapping, one object of a persistent class is related to one object of another persistent class. Here, we are going to create an example of one-to-one mapping using annotation. In this case, we are using bidirectional mapping, and no foreign key will be created in the primary table.

In this example, we will take two persistent classes, i.e., Student and Address. We are using bidirectional mapping, so that, one student can have one address and vice-versa. Here, we need to define @OneToOne annotation in the persistent classes.

Following are the steps to create the example:

  1. Create all  POJO classes

In this step, we are going to create persistent classes, i.e., Student.java and Address.java. Both the classes contain the reference of each other.

Student.java

Address.java

  • Create the configuration class

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 which 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

One-to-One Hibernate Mapping

TABLE- students

TABLE- students One-to-One Hibernate Mapping

Pin It on Pinterest

Share This