U
U
Urukhayy2016-01-29 16:59:30
Java
Urukhayy, 2016-01-29 16:59:30

How to organize such a multitype method?

public static void useLoadWithCriteria(Class<? extends AbstractHibernateClass> instance) {

        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        Session session = sessionFactory.openSession();

        Criteria criteria = session.createCriteria(instance.getClass());

        criteria.add(Restrictions.eq("age", 25));

        instance = (instance.getClass()) criteria.uniqueResult(); // Ошибка на строчку
    }

The last line has a class mismatch error.
uniqueResult returns Object.
The task is such that by passing an instance of any class that is inherited from AbstractHibernateClass, perform a selection for it, and write the result of the selection into this instance.
Also, perhaps someone will offer a more optimal version of the method with a sample for any class.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
achist, 2016-02-01
@Urukhayy

You pass an object of type Class to the method, you don’t need to call getClass on it, I doubt that it gives you what you expect;
And inside the method, assigning values ​​to the instance reference here does not make sense.
try the parameterized method:

public static <T extends AbstractHibernateClass> T useLoadWithCriteria(Class<T> instance) {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        Criteria criteria = session.createCriteria(instance);
        criteria.add(Restrictions.eq("age", 25));
        return = (T) criteria.uniqueResult();
}

Or something like this

A
Artem Vereschaka, 2016-01-29
@And3en

Try it with reflection.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question