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

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.sistema.hibernate.onetomanybidirxml.HibernateSession;
import org.sistema.hibernate.onetomanybidirxml.models.Player;

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

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

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

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

	}

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

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

}
