package com.javahonk;

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 {
	
	static SessionFactory sf = HibernateUtil.getSessionFactory();	

	public static void main(String[] args) {

		insertData();

		selectData();

	}

	private static void selectData() {
		
		Session session = sf.openSession();
		session.beginTransaction();
       
        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();
	}

	private static void insertData() {
		
		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");	
        session.save(mother);
        
        Child child=new Child();
        child.setFirstName("Tom");
        child.setLastName("Kay");
        child.setMother(mother);
        
        session.save(child);
        
        Child child2=new Child();
        child2.setFirstName("John");
        child2.setLastName("Kay");
        child2.setMother(mother);
        
        session.save(child2);
        
        session.getTransaction().commit();
        session.close();
	}

}
