Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a generic method to get data from database with Hibernate?

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?

like image 625
Dragon Avatar asked Jan 11 '23 15:01

Dragon


1 Answers

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);
like image 54
Konstantin Yovkov Avatar answered Jan 17 '23 03:01

Konstantin Yovkov