package com.javahonk;

import java.util.List;
import java.util.Set;

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

import com.javahonk.bean.Employee;
import com.javahonk.bean.Project;
import com.javahonk.util.HibernateUtil;

public class ManyToManyTest {
    
    static SessionFactory sf = HibernateUtil.getSessionFactory();

    public static void main(String[] args) {	
	
	insertData();
	
	selectInsertedData();

    }

    private static void selectInsertedData() {
	Session session = sf.openSession();
        session.beginTransaction();
       
        List<Employee> emList = session.createQuery("from Employee")
                .list();
        for (Employee employee : emList) {
            System.out.println("Employee table data:");
            System.out.println("First Name: "+employee.getFirstName()
                    +" Last Name: "+employee.getLastName()+"\n");
            System.out.println("Project table data:");
            Set<Project> childs=employee.getProjects();
            for (Project project : childs) {
        	System.out.println("Project Name: "
                        +project.getProjectName()+" Project Id: "
                                +project.getProjectId()+"\n");
	    }
           

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

    private static void insertData() {
	Session session = sf.openSession();
	
	session.beginTransaction();
	
	Employee employee = new Employee("Java","Honk");
	Employee employee2 = new Employee("Java2","Honk2");

	Project project = new Project("Trading System");
	Project project2 = new Project("Institutioanl Trading System");
	
	employee.getProjects().add(project);
	employee.getProjects().add(project2);
	
	employee2.getProjects().add(project);
	employee2.getProjects().add(project2);

	
	session.save(employee);
	session.save(employee2);

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

}
