package org.sistema.hibernate.onetoonebidirxml.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.sistema.hibernate.onetoonebidirxml.HibernateSession;
import org.sistema.hibernate.onetoonebidirxml.models.Service;

/**
 * implementation of ServiceDAOInterface
 * @author Eugenia Pérez
 * @email eugenia_perez@cuatrovientos.org
 */
public class ServiceDAO implements ServiceDAOInterface {

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

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

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

	}
	

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

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

}
