user2992380
user2992380

Reputation: 57

Hibernate createQuery: How to loop over the result

I have the following HQL statement:

select d.model, v.vendor from Device d, Vendor v where d.vendorId = v.id

and the following java code:

private List<Device> allDevices;
//Getter and Setter are created
 public List<Device> getAllDevices() {
    return allDevices;
}

public void setAllDevices(List<Device> allDevices) {
    this.allDevices = allDevices;
}

public List<Device> readDevices() {
    session = HibernateUtil.getSessionFactory().openSession();
    String hql = "select d.model, v.vendor from Device d, Vendor v where d.vendorId = v.id";
    Query query = session.createQuery(hql);
    List list = query.list();
    allDevices = new ArrayList();       
//Here comes the code, loop, for getting the values from the list !?!
[...]
session.close();
return allDevices;    
}

My Question is: How can I get the values from query.list() and add them to the allDevices ArrayList:

The class Device is a mapping class of the MySQL DB "device" table and has string column model and Integer column vendor_id. The vendor_id is the id of the "vendor" table. The "vendor" table has Integer column id and string column vendorname. I would like to show on the JSF page the model name and the corresponding vendor name instead of the vendor id.

My first attempt with the following loop is not working:

for (int i = 0; i < list.size(); i++) {
            device = (Device) list.get(i);
            allDevices.add(device);
        }

Can anyone help me out?

Upvotes: 0

Views: 2950

Answers (1)

M. Deinum
M. Deinum

Reputation: 124461

I suggest using JPA instead of plain hibernate, then you can use a TypedQuery and you are using standards. Should by quite easy to make the switch and you can then drop your HibernateUtil class

@PersistenceContext
private EntityManager em;

public List<Device> readDevices() {
    String hql = "select d.model, v.vendor from Device d, Vendor v where d.vendorId = v.id";
    TypedQuery<Device> query = em.createQuery(hql, Device.class);
    allDevices.addAll(query.getResultList());   
    return allDevices;    
}

Also you probably don't want this code in your JSF backed bean but in a service or repository class instead.

Upvotes: 2

Related Questions