
package org.sistema.hibernate.manytomanyunidirannotations.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.sistema.hibernate.manytomanyunidirannotations.HibernateSession;
import org.sistema.hibernate.manytomanyunidirannotations.models.BankAccount;

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

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

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

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

	}

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

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

}
