0

I'am tring to retrieve from my database (using JPA) for a given list of items name their id, my function wich called by my addFunction return just the id of the last item and ignore the rest!

public ArrayList<Integer> getListidItemByItemName()
  {
       try{
       EntityTransaction entityTrans=emm.getTransaction();
       entityTrans.begin();
          for (String val : listItem)  
          {
           System.out.println("my values"+val);
           javax.persistence.Query multipleSelect= em.createQuery("SELECT i.ItemId FROM Item i WHERE i.ItemName IN (:w)" );
           multipleSelect.setParameter("w", val);
           List ItemId =  new LinkedList();
           ItemId= multipleSelect.getResultList();
           listIdItem = new ArrayList(ItemId);
          }    
          entityTrans.commit();
          System.out.println("Id for given item name"+listIdItem);
          return listIdItem;
         }

         catch(Exception e)
        {
           e.printStackTrace();
        }

The result :

INFO: my valuesResponse Time
INFO: my valuesAssigned Group Response Time
INFO: Id for given item name[7]  //the id of the last item in the list

      return listIdItem;
  }

Where is the problem?

UPDATE: I have use the solution of mat and it worked fine

thank you

2 Answers 2

1
listIdItem = new ArrayList(ItemId);

This line replaces whatever you had in listIdItem with a new list. If you want to add to the listIdItem list, do something like:

listIdItem.addAll(ItemId);
Sign up to request clarification or add additional context in comments.

2 Comments

Move the print inside the loop to see if you are really getting more than one id (print the ItemId list on each iteration).
@ Mat,yes your right when I have printed the item inside the loop I see know that the function works fine ,but the problem in my other funtion wich add those item into the database!
0

You're overwriting your variable listIdItem in every iteration of the loop with a new ArrayList. So in the end listIdItem will only contain the last iteration's values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.