I have a function that add into my database (using JPA) a user and his items ,the relationship many-to- many. I have the following tables :
profilUser
item
associationProfileUserItem
on the GUI I enter the login and password of the user and I choose a list of names of items, I have worte a function recuperate id of Item BY their name (to add them to the association). the problem is that the function insert just the last item choosen for the user and ignore the rest!
My code:
public void addProfilUser()
{
try{
EntityTransaction entr=em.getTransaction();
entr.begin();
AssociationItemProfilPK ItemprofilPk=new AssociationItemProfilPK();
AssociationItemProfil Itemprofil=new AssociationItemProfil();
ProfilUser user=new ProfilUser();
user.setLogin(login);
user.setPassword(password);
em.persist(user);
for (Integer val : getListidItemByItemName())
{
ItemprofilPk.setItemId(val);
ItemprofilPk.setProfilId(user.getProfilUserId());
Itemprofil.setAssociationItemProfilPK(ItemprofilPk);
}
em.persist(Itemprofil);
entr.commit();
}
catch (Exception e )
{
System.out.println(e.getMessage());
System.out.println("Failed");
}
finally {
em.close();
emf.close();
}
}
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();
}