Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate 5.2 version -> A lot of Query methods deprecate?

I'm new to Hibernate.

I'm trying to get a list of first name and last name of all administrators.

There are two warnings in my following code. I already tried to search a lot online.

1) Query is a raw type. References to generic type Query should be parameterized.

2) The method list() from the type Query is deprecated.

public List<Object> loadAllAdmins() {
                List<Object> allAdmins = new ArrayList<Object>();
                try {
                        HibernateUtil.beginTransaction();

                        Query q = currentSession.createQuery("SELECT admin.firstName, admin.lastName from AdminBean admin");

                        allAdmins= q.list();

                        HibernateUtil.commitTransaction();
                } catch (HibernateException ex) {
                        System.out.println("List<AdminBean> loadAllPersons: HibernateException");
                }
                return allAdmins;
        }

But I see sample code like this all over the web. How should I solve these two problems?

Update

I just tried to use Criteria as suggested. It also says the list() method is deprecate for Criteria... It seems that a lot of methods are deprecate for both Query and Criteria, including uniqueResult() and others... Any suggestion how I should replace them?

like image 882
Chenya Zhang Avatar asked Jul 19 '16 14:07

Chenya Zhang


2 Answers

public List<Admin> getAdmins() {
    List<Admin> AdminList = new ArrayList<Admin>(); 
    Session session = factory.openSession();
    for (Object oneObject : session.createQuery("FROM Admin").getResultList()) {
        AdminList.add((Admin)oneObject);
    }
    session.close();
    return AdminList;
}

The warnings came from "Type Inference".

I had the similar problem. However, I found a solution without "SuppressWarnings".


Recently, I found out a shorter way to code the same things without type inference.

public List<Admin> getAdmins() {
    Session session = factory.openSession();
    TypedQuery<Admin> query = session.createQuery("FROM Admin");
    List<Admin> result = query.getResultList();
    session.close();
    return result;
}

Hope it helps.

like image 99
Pika Avatar answered Sep 21 '22 16:09

Pika


Don't import QUERY from org.hibernate (As its Deprecated now). Instead import from “org.hibernate.query” .Eclipse reference

like image 42
Aniket Warey Avatar answered Sep 22 '22 16:09

Aniket Warey