package gov.va.med.pharmacy.persistence;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class BaseDao<PK extends Serializable, T> {

	 private final Class<T> persistentClass;
     
	    @SuppressWarnings("unchecked")
	    public BaseDao(){
	        this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
	    }
	     
	    @Autowired
	    private SessionFactory inboundErxSessionFactory;
	 
	    protected Session getSession(){
	        return inboundErxSessionFactory.getCurrentSession();
	    }
	 
	    @SuppressWarnings("unchecked")
	    public T getByKey(long id) {
	        return (T) getSession().get(persistentClass, id);
	    }
	 
	    public void persist(T entity) {
	        
	    	Session session = getSession(); 
	    	
	    	session.persist(entity);
	    	
	    	session.flush();
            session.clear();
	    	
	    	
	    	
	    }
	    
	    public void update(T entity) {
	        
	    	Session session = getSession(); 
	    	
	    	session.update(entity);
	    	
	    	session.flush();
            session.clear();
	    	
	    	
	    	
	    }
	 
	    public void delete(T entity) {
	        getSession().delete(entity);
	    }
	     
	    protected Criteria createEntityCriteria(){
	        return getSession().createCriteria(persistentClass);
	    }
}
