package com.javahonk;

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

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.javahonk.bean.Child;
import com.javahonk.bean.Mother;
import com.javahonk.util.HibernateUtil;

public class OneToManyInsert {

	public static void main(String[] args) {
		
		SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
 
        Mother mother=new Mother();
        mother.setFirstName("Mary"); 
        mother.setLastName("Kay");
        mother.setCity("Edison");
        mother.setZip("10038");
        mother.setState("NJ");	
        
         
        Child child=new Child();
        child.setFirstName("Tom");
        child.setLastName("Kay");
        
        Child child2=new Child();
        child2.setFirstName("John");
        child2.setLastName("Kay");
        
        HashSet<Child> set1 = new HashSet<Child>();
        set1.add(child);
        set1.add(child2);        
         
        mother.setChilds(set1);
        session.save(mother);
       
         
        List<Mother> moList = session.createQuery("from Mother").list();
        for (Mother mother2 : moList) {
            System.out.println("Mother table data:");
            System.out.println("First Name: "+mother2.getFirstName()+" Last Name: "+mother2.getLastName()+" City: "+mother2.getCity()+" State: "+mother2.getState()+" Zip: "+mother2.getZip()+"\n");
            System.out.println("Child table data:");
            Set<Child> childs=mother2.getChilds();
            for (Iterator<Child> iterator = childs.iterator(); iterator.hasNext();) {
				Child child3 = (Child) iterator.next();
				System.out.println("First Name: "+child3.getFirstName()+" Last name: "+child3.getLastName()+"\n");
				
			}
            
        }

        session.getTransaction().commit();
        session.close(); 

	}

}
