Sergei Sergei - 1 month ago 13
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 :

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

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

public BasicDAOImpl() {
}

@Autowired
SessionFactory sessionfactory;

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

return list;
}


And I have :
WorkoutDAOImpl extende BasicDAOImpl

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


Bean:

@Bean
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

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() {
        super(Workout.class);
    }
}