I have generic method for add, update and delete entities. But I also want to use generics for retrieving data.
Here is my methods to get data:
public static List<ClassA> getAllClassAData() {
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(ClassA.class);
return criteria.list();
}
public static List<ClassB> getAllClassBData() {
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(ClassB.class);
return criteria.list();
}
public static List<ClassC> getAllClassCData() {
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(ClassC.class);
return criteria.list();
}
I tried to make something like this:
public static <T> List<T> getAllData() {
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(???.class); //Here is where I'm stuck
return criteria.list();
}
And I stuck with passing the class as arg for criteria creation:
Criteria criteria = session.createCriteria(Generic.class);
How can I make JVM know what class I'm trying to pass during criteria creation?
Your generic method should look more like :
public static <T> List<T> getAllData(Class<T> clazz) {
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(clazz);
return criteria.list();
}
and you should invoke it like:
List<ClassA> list = getAllData(ClassA.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With