Hibernate: Storing all values retrieved from Query to ArrayList

时间:2016-04-25 09:24:23

标签: java hibernate

My issue is that I am getting the results of only one row, that also three times. I want to retrieve all the data which has stock less than 10. How do I add the object data to the arraylist?

        String lowStock = "SELECT MedcineID, MName, Quantity FROM medcineinventory WHERE Quantity < :stock";
        SQLQuery query = session.createSQLQuery(lowStock);

        query.setParameter("stock", 10);
        List<Object[]> stocks = query.list();
        ArrayList<Inventory> allResults = new ArrayList<Inventory>();
            Inventory iv = new Inventory();

            for(Object[] data : stocks){

                iv.setMedcineID((Integer) data[0]);
                iv.setMName((String) data[1]);
                iv.setQuantity((Integer)data[2]);

                allResults.add(iv);

            }       

        tx.commit();
        session.close(); 

    return allResults;

2 个答案:

答案 0 :(得分:2)

                for(Object[] data : stocks){
                Inventory iv = new Inventory();
                iv.setMedcineID((Integer) data[0]);
                iv.setMName((String) data[1]);
                iv.setQuantity((Integer)data[2]);

                allResults.add(iv);

                }  

Create a new inventory object inside the for loop and add that to your arraylist. Replace your for loop with this

答案 1 :(得分:2)

You have to move your Inventory iv = new Inventory(); inside the loop:

for(Object[] data : stocks){
    Inventory iv = new Inventory();
    iv.setMedcineID((Integer) data[0]);
    iv.setMName((String) data[1]);
    iv.setQuantity((Integer)data[2]);
    allResults.add(iv);
}

That's because every time you go through the list of results you alter the data of the initial iv and add a new entry to the result list. So in the end you have three entries in your final list with the same values which represent the last element of the retrieved data.

Moving the creation of iv inside the loop creates new elements every time.