/**
 * 
 */
package org.sistema.hibernate.onetomanyunidirannotations.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.sistema.hibernate.onetomanyunidirannotations.HibernateSession;
import org.sistema.hibernate.onetomanyunidirannotations.models.Team;

/**
 * implementation of teamDAOInterface
 * @author Eugenia Pérez
 * @email eugenia_perez@cuatrovientos.org
 */
public class TeamDAO implements TeamDAOInterface {

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

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

	/*
	 * inserts a new team in database
	 * team must come with the idcar set 
	 * @param new team
	 */
	public void insert(Team team) {
	    SessionFactory sessionFactory = HibernateSession.getSessionFactory();
	    Session session = sessionFactory.openSession();
	    session.beginTransaction();
	 
	    session.persist(team);    
	    
	    session.getTransaction().commit();	         
	    session.close();

	}

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

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

}
