Many-to-One Example Hibernate


Many-to-One Hibernate

Note: It is advised to read One-to-Many association before going this.

You have seen one example on one-to-many involving dept (corresponding Dept class) and employee (corresponding Employee class) tables. You have achieved this in Java by adding many objects of Employee to Dept object through Set.

Many-to-one is also the same but viewing perspective (side) is different. Here, we see from Employee side. Many employees belong to one dept (earlier one dept contains many employees). This is many-to-one, just reverse viewing of one-to-many. How to achieve this?

The same Dept and Employee bean classes and tables dept and employee are used. Tables have the same columns. Make small changes in the variables of Dept and Employee classes.

1. Remove java.util.Set from Dept.

2. Add one Dept object in Employee class (this is how many to one association is achieved).

That is all. But remember, the mapping file changes but not configuration file.

1. File Name: Dept.java

The same Dept bean of one-to-many is used with a small change that Set variable is removed.

public class Dept 
{
  private int deptId;
  private String deptName;

  public Dept() 
  {
    // TODO Auto-generated constructor stub
  }
  public int getDeptId() 
  {
    return deptId;
  }
  public void setDeptId(int deptId) 
  {
    this.deptId = deptId;
  }
  public String getDeptName() 
  {
    return deptName;
  }
  public void setDeptName(String deptName) 
  {
    this.deptName = deptName;
  }
}

Observe, both import java.util.Set and variable private Set employees are removed from Dept class of one-to-many.

2. File Name: Employee.java

The same Employee bean of one-to-many is used with a very small change of addition of Dept object variable.

public class Employee 
{
  private int employeeId;
  private String employeeName;
  private Dept myDept;

  public Employee() 
  {
    // TODO Auto-generated constructor stub
  }
  public int getEmployeeId() 
  {
    return employeeId;
  }
  public void setEmployeeId(int employeeId) 
  {
    this.employeeId = employeeId;
  }
  public String getEmployeeName() 
  {
    return employeeName;
  }
  public void setEmployeeName(String employeeName) 
  {
    this.employeeName = employeeName;
  }
  public Dept getMyDept() 
  {
    return myDept;
  }
  public void setMyDept(Dept myDept) 
  {
    this.myDept = myDept;
  }
}

private Dept myDept;

Observe the addition of object myDept of Dept class in Employee class. Observe slowly the difference between one-to-many and many-to-one. I feel, comparison is the better way of understanding.

3. File Name: hibernate.cfg.xml








  
    org.hibernate.dialect.Oracle9Dialect
  
  
    jdbc:oracle:thin:@localhost:1521:orcl1
  
  scott
  tiger
  
    oracle.jdbc.driver.OracleDriver
  
  
    SNRaoConnection
  
  update
  true

  



4. File Name: dept.hbm.xml



	



  
  



  
  
  



<many-to-one> XML element is used to establish the many-to-one relationship between the Dept and Employee classes.

cascade="all"

The cascade attribute does the required operations to the associated Java class. all value set to cascade element, cascades all the operations. For example, if you save the Employee object, the corresponding Dept object also will be saved automatically.

5. File Name: Client Program: InsertClient.java (inserts records in dept and employee tables)

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
 
public class InsertClient 
{
  public static void main(String args[])
  {
    Configuration c = new Configuration();
    c.configure("hibernate.cfg.xml"); 
 
    SessionFactory sf = c.buildSessionFactory();
    Session s = sf.openSession();        
 
    Dept d1 = new Dept();
    d1.setDeptId(4567);
    d1.setDeptName("Stores");
 
    Employee e1= new Employee();
    e1.setEmployeeId(100);
    e1.setEmployeeName("S N Rao");
    e1.setMyDept(d1);
 
    Employee e2= new Employee();
    e2.setEmployeeId(101);
    e2.setEmployeeName("Sridhar");
    e2.setMyDept(d1);
 
    Employee e3 = new Employee();
    e3.setEmployeeId(102);
    e3.setEmployeeName("Jyostna");
    e3.setMyDept(d1);
 
    Transaction tx = s.beginTransaction();
    s.save(e1);  
    s.save(e2);
    s.save(e3);
 
    tx.commit();
    s.close();
    System.out.println("Many to one completed");
    sf.close();
  }
}

You can observe the same tables of one-to-many but the inserting mode is different. In one-to-many, the records were inserted through Dept class and now from Employee class.

image

Console output screen

image

After inserting activity, let us write how to fetch the record from tables.

File Name: RetrieveRecord.java

import org.hibernate.Session;  
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class RetrieveRecord 
{
  public static void main(String args[])
  {
    Configuration c = new Configuration();
    c.configure("hibernate.cfg.xml"); 
 
    SessionFactory sf = c.buildSessionFactory();
    Session s = sf.openSession();        
 
    Employee e1 = (Employee)s.get(Employee.class, new Integer(100));
        
    System.out.println("Employee ID: " + e1.getEmployeeId());
    System.out.println("Employee Name: " + e1.getEmployeeName());
        
    Dept d1 = e1.getMyDept();
    System.out.println("Employee Department ID: " + d1.getDeptId());
    System.out.println("Employee Department Name: " + d1.getDeptName()); 
 
    s.close();
    System.out.println("many to one select is completed");
    sf.close();       
  }
}

Console output screen.

Many-to-One Hibernate

After retrieving, let us write one more client program to delete the record. Before this, try to answer the following question, necessary to understand the deletion of record.

Does the following code works?

Session s = sf.openSession();        
Employee e1 = (Employee) s.get(Employee.class, new Integer(100));
Transaction tx = s.beginTransaction();
s.delete(e1);
tx.commit();

Never, it gives an exception of "integrity constraint (SCOTT.SYS_C005342) violated – child record found". The child table employee has a foreign key constraint and for this reason Employee e1 object cannot be deleted.

Then how to delete the Dept and Employee records?

Following is the code that deletes.

File Name: DeleteRecord.java

import java.util.Iterator;  
import org.hibernate.Query;  
import org.hibernate.Session;
import org.hibernate.SessionFactory;  
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
 
public class DeleteRecord 
{
  public static void main(String args[])
  {
    Configuration c = new Configuration();
    c.configure("hibernate.cfg.xml"); 
 
    SessionFactory sf = c.buildSessionFactory();
    Session s = sf.openSession();       
    Transaction tx = s.beginTransaction();
 
    Query q = s.createQuery("FROM Employee");
    Employee e1 = null;
    Iterator it = q.iterate();
    while(it.hasNext())
    {
      e1 = (Employee) it.next();
      s.delete(e1);
    }
    
    Dept d1 = e1.getMyDept();
    s.delete(d1);
        
    tx.commit();
    s.close();
    System.out.println("Deletion is done successfully");
    sf.close();       
  }
}

It is a small technique. First kill of all the Employee objects associated with the Dept. There are three Employee IDs with 100, 101 and 102 (see our insertion code, first client program). All the three Employee objects are deleted with Iterator and finally after the while loop, Dept object is deleted. Confirm the action, with the database.

Many-to-One Hibernate

Leave a Comment

Your email address will not be published.