/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.csu.sdmx.dao;

import java.io.Serializable;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author themi
 * @param <E>
 * @param <PK>
 */

@Component
@Transactional
public abstract class DaoSupportImp<E, PK extends Serializable> implements DaoSupport<E, PK>{
    
    @Autowired
   protected SessionFactory sessionFactory;

    protected Session getCurrentSession(){
       return sessionFactory.getCurrentSession();
    } 

    protected Class<E> entityClass;
    
    public DaoSupportImp(Class<E> entityClass) {
        this.entityClass = entityClass;
    }
    
    protected String getClassName(){
        return entityClass.getSimpleName();
    }
    
    @Override
    public final E find(final PK id) {
        return (E) getCurrentSession().get(entityClass, id);
    }
  
    @Override
    public final List<E> list() {
        return getCurrentSession().createCriteria(entityClass).list();
    }

    @Override
    public void delete(PK pk) {
        E el = find(pk);
        getCurrentSession().delete(el);
        getCurrentSession().flush();
    }

    
    @Override
    public boolean insert(E entity) {
        try{
            getCurrentSession().save(entity);
            return true;
        }catch(HibernateException ex){
            ex.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean update(E entity) {
        try{ 
            getCurrentSession().update(entity);
            return true;
        }catch(HibernateException ex){
            ex.printStackTrace();
            return false;
        }
    }
}
