Example 2:

For Retrieving the records from Employee and Address tables using Many-to-One relationship


package dao;

import java.util.Iterator;
import java.util.Set;

import org.hibernate.Session;
import session.HibernateSessionFactory;
import com.mapping.Address;
import com.mapping.Employee;

public class RetrieveRecordsfrommanyTone {
       public static void main(String[] args) {
             
Session session=HibernateSessionFactory.getSession();
Address address=new Address()     session.load(address,1);

       System.out.println(address.getStreetName());
       System.out.println(address.getCityName());
       System.out.println(address.getStateName());
       System.out.println(address.getZipcode());
      
       Set set=address.getEmployees();
      
       Iterator it=set.iterator();
      
       while(it.hasNext()){
             
              Employee employee=(Employee)it.next();           System.out.println("Emp Id is :"+employee.getId());       System.out.println(employee.getFirstName());       System.out.println(employee.getLastName());
       System.out.println(employee.getSalary());
                    
       //two employee having one address
       }
                          
       }
}

Output:

 Records printed here
 
//if Exception occurs like….
or.hibernate.ObjectNotFoundExecption

session.load(address,2);
 means address id 2 is not exist in address table

0 comments:

Post a Comment