Sergei Sergei - 1 year ago 76
Java Question

Generics with Hibernate when should I have to use criteria?

I tried to use generics with my code.
I have Dao that get info from BD :

public class BasicDAOImpl<T> implements BasicDAO<T> {
private Class<T> type;

public BasicDAOImpl(Class<T> type) {this.type = type;

public BasicDAOImpl() {

SessionFactory sessionfactory;

public List<T> getAllByKey(int id) {
List<T> list = new ArrayList<>();
Session session = sessionfactory.getCurrentSession();
Criteria criteria = session.createCriteria(type);
criteria.add(Restrictions.eq("parentid", id));
}catch (HibernateException e){}

return list;

And I have :
WorkoutDAOImpl extende BasicDAOImpl

public class WorkoutDAOImpl extends BasicDAOImpl<Workout> implements WorkoutDAO {}


public WorkoutDAO workoutDAO(){
return new WorkoutDAOImpl();

I write in my code:
"workoutDAO.getAllByKey(int 2) "
and get error java.lang.NullPointerException in Criteria criteria = session.createCriteria(type). Why?
If write Criteria criteria = session.createCriteria(Workout.class), then dont get any errors.

PS/ Sorry or my english :)

Answer Source

Workout.class isn't passed to BasicDAOImpl from your WorkoutDAOImpl so Class<T> type isn't initialized and you get NullPointerException. Add no-argument constructor:

public class WorkoutDAOImpl extends BasicDAOImpl<Workout> implements WorkoutDAO {

    public WorkoutDAOImpl() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download