package org.sistema.hibernate.manytomanybidirxml.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.sistema.hibernate.manytomanybidirxml.HibernateSession;
import org.sistema.hibernate.manytomanybidirxml.models.Customer;

/**
 * implementation of StudentDAOInterface
 * @author Eugenia Pérez
 * @email eugenia_perez@cuatrovientos.org
 */
public class CustomerDAO implements CustomerDAOInterface {

	/* 
	 * selects one Student by Id
	 * @param id
	 * @return Student
	 */
	public Customer selectById(Long id) {
	    SessionFactory sessionFactory = HibernateSession.getSessionFactory();
	    Session session = sessionFactory.openSession();
	 
	    Customer customer = (Customer) session.get(Customer.class, id);
	    
	    session.close();
	    return customer;
	}

	/*
	 * retrieves all Students from db
	 * @return List of Students
	 */
	public List<Customer> selectAll() {
	    SessionFactory sessionFactory = HibernateSession.getSessionFactory();
	    Session session = sessionFactory.openSession();
	 
	    List<Customer> customeres = session.createQuery("from Customer").list();
	    
	    session.close();
	    return customeres;
	}

	/*
	 * inserts a new Student in database
	 * retrieves generated id and sets to Student instance
	 * @param new Student
	 */
	public void insert(Customer customer) {
	    SessionFactory sessionFactory = HibernateSession.getSessionFactory();
	    Session session = sessionFactory.openSession();
	    session.beginTransaction();
	
	    session.persist(customer);
	         
	    session.getTransaction().commit();
	    session.close();

	}

	/*
	 * updates Student
	 * @param Student to update
	 */
	public void update(Customer customer) {
	    SessionFactory sessionFactory = HibernateSession.getSessionFactory();
		    Session session = sessionFactory.openSession();	 
		    session.beginTransaction();
		 
		    session.merge(customer);
		 
		    session.getTransaction().commit();
		    session.close();
	}

	/*
	 * delete given Student
	 * @param Student to delete
	 */
	public void delete(Customer customer) {
	    SessionFactory sessionFactory = HibernateSession.getSessionFactory();
	    Session session = sessionFactory.openSession();	    
	    session.beginTransaction();
	    
	    session.delete(customer);
	 
	    session.getTransaction().commit();
	    session.close();
	}

}
