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

Chenya Zhang picture Chenya Zhang · Jul 19, 2016 · Viewed 30.5k times · Source

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?

Answer

Pika picture Pika · Sep 27, 2016
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.