So far I have this:
my DAO:
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import util.HibernateUtil;
public abstract class AbstractDAO<T> {
private Class classe;
private Session session;
public AbstractDAO(){
this.classe = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
protected Session getSession(){
if(this.session == null || !this.session.isOpen()){
this.session = HibernateUtil.getSessionFactory().openSession();
}
return this.session;
}
public void save(T t){
getSession().beginTransaction();
getSession().save(t);
getSession().close();
}
public void delete(T t){
getSession().beginTransaction();
getSession().delete(t);
getSession().close();
}
public void alter(T t){
getSession().beginTransaction();
getSession().update(t);
getSession().close();
}
public List<T> findAll(T t){
return getSession().createCriteria(this.classe).list();
}
/**
* Metodo responsavel por recuperar todos os objetos de uma tabela da base de dados de acordo
* com o exemplo passado.
*
* @param filtro
* @param matchMode
* @param ignoreCase
* @return lista
*/
public List<T> findByExample(T filtro, MatchMode matchMode, boolean ignoreCase){
org.hibernate.criterion.Example example = org.hibernate.criterion.Example.create(filtro);
if(matchMode != null){
example = example.enableLike(matchMode);
}
if(ignoreCase){
example = example.ignoreCase();
}
return getSession().createCriteria(this.classe).add(example).list();
}
}
my hibernate util:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
meu main:
public static void main(String[] args) {
Departamento depart = new Departamento();
AbstractDAO<Departamento> padrao = new DepartamentoDAO();
padrao.findAll(depart);
System.out.println(padrao);
}
I have this error:
Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType at dao.AbstractDAO.(AbstractDAO.java:16) at dao.DepartamentoDAO.(DepartamentoDAO.java:17) at view.eeee.main(eeee.java:12)
Not sure if I did it best if someone could help me how to adjust the code