1
Hello,
I am starting to develop a web application with spring+Hibernate framework, I started for an example that contained following class:
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class AbstractDao<PK extends Serializable, T> {
private final Class<T> persistentClass;
@SuppressWarnings("unchecked")
public AbstractDao(){
this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
}
@Autowired
private SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
@SuppressWarnings("unchecked")
public T getByKey(PK key) {
return (T) getSession().get(persistentClass, key);
}
public void persist(T entity) {
getSession().persist(entity);
}
public void delete(T entity) {
getSession().delete(entity);
}
protected Criteria createEntityCriteria(){
return getSession().createCriteria(persistentClass);
}
}
It is an abstract DAO to be used for the remaining Daos, I cannot understand the generics that the class receives:
public abstract class AbstractDao<PK extends Serializable, T>
And the line that’s on the builder
this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
I’m not comfortable with java generics. They can help explain the logic of this class?
Thank you.
The line you found complicated is a gambit to circumvent the type Erasure Java. Because Java deletes generic type information, this gambit is necessary to know which one it is.
– Piovezan