One to One and Many to One Mapping in Hibernate by R4R Team

We can map to database One to One association using XML mapping approach with the application. In the One to One association we use to foregin key in which the parent table (WORKER) refer to child table (WORKER_ADDRESS). It has a condition it can done through WORKER TO WORKER_ADDRESS but it can not possible WORKER_ADDRESS TO WORKER.

Before creating the application on the One to One mapping we need to create a database and inside the two table.

Step 1. create database hibernate_pro;
Step 2. create table

create table WORKER (
   id INT NOT NULL auto_increment primary key,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   address    INT NOT NULL,
);

Step 3. Create another table for One to One mapping
create table WORKER_ADDRESS (
   id INT NOT NULL auto_increment primary key,
   street_name VARCHAR(40) default NULL,
   city_name VARCHAR(40) default NULL,
   state_name VARCHAR(40) default NULL,
   zipcode VARCHAR(10) default NULL,
);

A one-to-one association is similar to many-to-one association.But has a difference that is column will be set as unique. For example an worker_address object can be associated with a single worker object.

Step 4. create POJO class (Worker is the pojo class which is used to persist the object WORKER table and it has variable of WORKER_ADDRESS type ) It is used to create the setter method and getter method for the seting the value and geting the value

import java.util.*;

public class Worker{
   private int id;
   private String firstName; 
   private String lastName;   
   private int salary;
   private Address address;

   public Worker() {}
   public Worker(String fname, String lname, int salary, Address address ) 
    {
      this.firstName = fname;
      this.lastName = lname;
      this.salary = salary;
      this.address = address;
   }
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName( String first_name ) {
      this.firstName = first_name;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName( String last_name ) {
      this.lastName = last_name;
   }
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }

   public Address getAddress() {
      return address;
   }
   public void setAddress( Address address ) {
      this.address = address;
   }
}

Step 5. Create the Another POJO class for the address object can be stored and retrieved into the WORKER_ADDRESS table.

import java.util.*;

public class Worker_Address{
   private int id;
   private String street;     
   private String city;     
   private String state;    
   private String zipcode; 

   public Worker_Address() {}
   public Worker_Address(String street, String city, String state, String zipcode) {
      this.street = street; 
      this.city = city; 
      this.state = state; 
      this.zipcode = zipcode; 
   }
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getStreet() {
      return street;
   }
   public void setStreet( String street ) {
      this.street = street;
   }
   public String getCity() {
      return city;
   }
   public void setCity( String city ) {
      this.city = city;
   }
   public String getState() {
      return state;
   }
   public void setState( String state ) {
      this.state = state;
   }
   public String getZipcode() {
      return zipcode;
   }
   public void setZipcode( String zipcode ) {
      this.zipcode = zipcode;
   }
   
}

Step 6. Hibernate Mapping File

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Worker" table="WORKER">
      <meta attribute="class-description">
         This class contains the WORKER detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
      <many-to-one name="address" column="address" unique="true" 
       class="Address" not-null="true"/>
   </class>

   <class name="Worker_Address" table="WORKER_ADDRESS">
      <meta attribute="class-description">
         This class contains the address detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="street" column="street_name" type="string"/>
      <property name="city" column="city_name" type="string"/>
      <property name="state" column="state_name" type="string"/>
      <property name="zipcode" column="zipcode" type="string"/>
   </class>

</hibernate-mapping>

Which tag is used in the mapping file which detailed are given below:

@Entity Annotation:

The EJB 3 annotations standard

Step 1: In the first step we have to import javax.persistence

Step 2: When we used the @Entity annotation to the HibernateMapping class it marked class to as an entity bean, so it must have a no-argument constructor that is visible with at least protected scope.

@Table Annotation:

@Table annotation allows to specify the details of the table that will be used to persist the entity in the database.

@Table annotation provides four attributes allowing override the name of the table, its catalogue, and its schema, and enforce unique constraints on columns in the table.

@Id and @GeneratedValue Annotations:

Each entity bean always will have a primary key, which annotated on the class with the @Id annotation. The primary key can be a single field or a combination of multiple fields depending on table structure.

By default, @Id annotation will automatically determine the most appropriate primary key generation strategy to be used but can override this by applying the @GeneratedValue annotation which takes two parameters strategy and generator, that is default key generation strategy.

@Column Annotation:

element maps the unique ID attribute in class to the primary key of the database table. Attribute name of the id element refers to the property in the class and the column attribute refers to the column in the database table. Attribute type holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.@Column annotation is used to specify the details of the column to which a field or property will be mapped. You can use column annotation with the following most commonly used attributes:

Some common attribute are given below:

Name attribute permits the name of the column to be explicitly specified.

Length attribute permits the size of the column used to map a value articularly for a String value.

Nullable attribute permits the column to be marked NOT NULL when the schema is generated.

Uniqueattribute permits the column to be marked as containing only unique values.


Step 7. Now create a class which contain main() because without main() method we can run the application.

import java.util.*;
 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ManageWorker {
   private static SessionFactory factory; 
   public static void main(String[] args) {
      try{
         factory = new Configuration().configure().buildSessionFactory();
      }catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }
      ManageWorker MW = new ManageWorker();

      /* Let us have one address object */
      Worker_Address address1 = ME.addWorker_Address("Kodapur","Dellhi","AP","5302");

      /* Add worker records in the database */
      Integer empID1 = ME.addWorker("Saroj", "Kumar", 4000, address1);

      /* Let us have another address object */
      Worker_Address address2 = MW.addWorker_Address("Patna","Ambehta","UP","2020");
  
    /* Add another Worker record in the database */
      Integer empID2 = MW.addWorker("Pradeep", "Kumar", 13000, address2);

      /* List down all the employees */
      MW.listEmployees();

      /* Update employee's salary records */
      MW.updateEmployee(empID1, 5000);

      /* List down all the Worker */
      MW.listEmployees();

   }

   /* Method to add an address record in the database */
   public Address addAddress(String street, String city, String state, String zipcode) {
      Session session = factory.openSession();
      Transaction tx = null;
      Integer addressID = null;
      Worker_Address address = null;
      try{
         tx = session.beginTransaction();
         address = new Address(street, city, state, zipcode);
         addressID = (Integer) session.save(address); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
      return address;
   }

   /* Method to add an Worker record in the database */
   public Integer addWorker(String fname, String lname, int salary, Address address){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer workerID = null;
      try{
         tx = session.beginTransaction();
         Worker worker = new Worker(fname, lname, salary, address);
         workerID = (Integer) session.save(worker); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
      return workerID;
   }

   /* Method to list all the worker detail */
   public void listWorker( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Worker").list(); 
         for (Iterator iterator = worker.iterator(); iterator.hasNext();){
            Worker worker = (Worker) iterator.next(); 
            System.out.print("First Name: " + worker.getFirstName()); 
            System.out.print("  Last Name: " + worker.getLastName()); 
            System.out.println("  Salary: " + worker.getSalary());
            Worker_Address add = worker.getAddress();
            System.out.println("Address ");
            System.out.println("\tStreet: " +  add.getStreet());
            System.out.println("\tCity: " + add.getCity());
            System.out.println("\tState: " + add.getState());
            System.out.println("\tZipcode: " + add.getZipcode());
         }
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
   /* Method to update salary for an worker */
   public void updateWorker(Integer WorkerID, int salary ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Worker worker = (Worker)session.get(Worker.class, WorkerID); 
         Worker.setSalary( salary );
         session.update(worker);
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
}

Step 7. After the doing all above step now we have reach on the comilation and run step for this we have to follow the some basic step those are below:


Step 1. Create hibernate.cfg.xml configuration file.

Step 2. Create Worker.hbm.xml mapping file.

Step 3. Create Worker.java source file.

Step 4. Create Worker_Address.java source file.

Step 5. Create ManageWorker.java source file.

Step 6. Execute ManageWorker binary to run the program.
     
         
     
     
     
     
     
   

Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!