Monday, 27 April 2020

One to many


1. http://www.mkyong.com/hibernate/different-between-cascade-and-inverse/
2. http://viralpatel.net/blogs/hibernate-one-to-many-xml-mapping-tutorial/
3. http://www.mkyong.com/hibernate/inverse-true-example-and-explanation/
4.http://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/
5. http://technicalmumbojumbo.wordpress.com/2007/08/18/investigating-hibernate-associations-one-to-many/



CREATE TABLE hibdept
(
id number primary key,
name varchar2(20)
);

create table hibemp
(
id number primary key,
name varchar2(30) ,
deptid number ,
constraint consthibemp FOREIGN KEY (deptid) REFERENCES hibdept(id)
)

create sequence hibdept_seq
create sequence hibemp_seq

1. Department.java


package dptemp;
import java.util.Set;

public class Department {
int id;
String name;
Set employees;


public Department() {
super();
}

public Department(String name) {
super();

this.name = name;
}
   getter/setter
}




2. Employee.java

package dptemp;

public class Employee {
int empid;
String empname;

Department department;



public Employee() {
super();
}


public Employee(String empname) {
super();
this.empname = empname;
}

getter / setter

}


3. department.hbm.xml


<?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 auto-import="false" package="dptemp">
   <class name="dptemp.Department" table="hibdept">
      <meta attribute="class-description">
         This class contains the department detail.
      </meta>
      <id name="id" type="int" column="id">
      <generator class="sequence">
                <param name="sequence">hibdept_seq</param>
            </generator>      
      </id>
      <set name="employees" cascade="all" inverse="true" lazy="true" fetch="select">
         <key column="deptid"/>
         <one-to-many class="dptemp.Employee"/>
      </set>
      <property name="name" column="name" type="string"/>
   
   </class>

   <class name="dptemp.Employee" table="hibemp">
      <meta attribute="class-description">
         This class contains the certificate records.
      </meta>
      <id name="empid" type="int" column="id">
         <generator class="sequence">
                <param name="sequence">hibemp_seq</param>
         </generator>
      </id>
      <property name="empname" column="name" type="string"/>
   
      <many-to-one name="department" class="dptemp.Department" fetch="select">
            <column name="deptid" not-null="true" />
      </many-to-one>
     
   </class>

</hibernate-mapping>


4. main


package dptemp;


import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import dptemp.Employee;
import dptemp.Department;

public class Main {

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);
     }
     Main ME = new Main();
   
     HashSet<Employee> employees1 = new HashSet<Employee>();
     Employee e1 = new Employee("A1");
     Employee e2 = new Employee("B1");
     Employee e3 = new Employee("C1");
     employees1.add(e1);
     employees1.add(e2);
     employees1.add(e3);
   
   
   
     int deptid1 = ME.addDepartmentEmployee("Department1", employees1);
     System.out.println("dept1 = "+ deptid1);
   
     HashSet<Employee> employees2 = new HashSet<Employee>();
     Employee e21 = new Employee("A2");
     Employee e22 = new Employee("B2");
     Employee e23 = new Employee("C2");
     employees2.add(e21);
     employees2.add(e22);
     employees2.add(e23);
   
     int deptid2 = ME.addDepartmentEmployee("Department2", employees2);      
     System.out.println("dept2 = "+ deptid2);
 
     ME.displayAll();
   


     Employee e22 = new Employee("D1");
     ME.addEmployee(45, e22);
     System.out.println("Record added");
     ME.displayAll();
   
     System.out.println("showing department no " + 48);
     ME.displayDepartmentName(48);
   
     System.out.println("showing department no " + 81);
     ME.displayDepartmentNameFromEmployeeid(81);

}


public int addDepartmentEmployee(String deptname , HashSet<Employee> employees){
Department department = new Department(deptname);

for(Iterator<Employee> it = employees.iterator();it.hasNext();)
{
Employee e = it.next();
e.setDepartment(department);
}

department.setEmployees(employees);
int departmentid =0;

Session session = factory.openSession();
     Transaction tx = null;
   
     try{
        tx = session.beginTransaction();      
        departmentid = (Integer) session.save(department);
        tx.commit();
     }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
     }finally {
        session.close();
     }
     return departmentid;

}

public void displayAll()
{
try{
Session session = factory.openSession();
List<Department> departments =(List<Department>) session.createQuery("FROM dptemp.Department").list();
Iterator<Department> it =(Iterator<Department>) departments.iterator();
while(it.hasNext()){
Department dept = it.next();
System.out.println("\n\nDepartment id =" + dept.getId() + " Name = " + dept.getName());

Iterator iti = dept.getEmployees().iterator();
while(iti.hasNext()){
Employee emp = (Employee)iti.next();
System.out.println("     emp id =" + emp.getEmpid() + " Name = " + emp.getEmpname());
}
}
session.close();

}
catch(Exception e){
e.printStackTrace();
}
}

public void displayDepartmentName(int deptid)
{
try{
Session session = factory.openSession();
Query q = session.createQuery("FROM dptemp.Department d where d.id = ?");
q.setInteger(0, deptid);


List<Department> departments = q.list();  //(List<Department>) session.createQuery("FROM dptemp.Department").list();
Iterator<Department> it =(Iterator<Department>) departments.iterator();
while(it.hasNext()){
Department dept = it.next();
System.out.println("\n\nDepartment id =" + dept.getId() + " Name = " + dept.getName());

Iterator iti = dept.getEmployees().iterator();
while(iti.hasNext()){
Employee emp = (Employee)iti.next();
System.out.println("     emp id =" + emp.getEmpid() + " Name = " + emp.getEmpname());
}
}
session.close();

}
catch(Exception e){
e.printStackTrace();
}
}

public void displayDepartmentNameFromEmployeeid(int empid)
{
try{
Session session = factory.openSession();
Query q = session.createQuery("FROM dptemp.Employee e where e.empid = ?");
q.setInteger(0, empid);


List<Employee> employees = q.list();  //(List<Department>) session.createQuery("FROM dptemp.Department").list();
Iterator<Employee> it =(Iterator<Employee>) employees.iterator();
while(it.hasNext()){
Employee emp = it.next();
System.out.println("\n\n Employee id =" + emp.getEmpid()+ " Name = " + emp.getEmpname());

Department d = emp.getDepartment();
System.out.println("\n\n its Department id =" + d.getId() + " Name = " + d.getName());

}
session.close();

}
catch(Exception e){
e.printStackTrace();
}
}

public void addEmployee(int deptid , Employee  employee){



Session session = factory.openSession();
     Transaction tx = null;
   
     try{
        tx = session.beginTransaction();
     
        Department d = (Department) session.load(Department.class, deptid);
        d.getEmployees().add(employee);
        session.saveOrUpdate(d);
        tx.commit();
     }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
     }finally {
        session.close();
     }
   

}





}