package isrp.hibernate.model.dao;

import isrp.hibernate.model.util.HibernateUtil;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Criteria;

/**
 * Implementacja interfejsu definiujacego podstawowe operacje dla DAO (patrz
 * rozdzial 2)
 */
public abstract class GenericDao implements GenericDaoInterface {
	@SuppressWarnings("unchecked")
	protected Class persistedClass;
	protected Session session;

	@SuppressWarnings("unchecked")
	public GenericDao(Class persistedClass) {
		SessionFactory factory = HibernateUtil.getSessionFactory();
		this.session = factory.getCurrentSession();
		this.persistedClass = persistedClass;
	}

	public Object findById(int id) {
		Object object = (Object) session.get(persistedClass, id);
		return object;
	}

	public void save(Object object) {
		session.save(object);
	}

	public void saveOrUpdate(Object object) {
		session.saveOrUpdate(object);
	}

	public void delete(Object object) {
		session.delete(object);
	}

	@SuppressWarnings("unchecked")
	public List findAll() {
		Criteria criteria = session.createCriteria(persistedClass);
		return criteria.list();
	}

}
