6 Replies Latest reply: Jan 19, 2012 4:22 AM by gimbal2 RSS

    How do you update a collection if some exist and some are new?

    865480
      Hi there,

      I have an entity bean property which is a collection of another entity. I have not been able to find any way to deal with updating a collection where some of the objects in the collection already exist in the database, and some are newly added. As an example, imagine a web page where a user can enter the universities they attended. They may have gone through a reg page and selected just one. Now they are back to add more. So the first one they selected shows up on the edit page, and they now add some more via some + button or something. When they hit SAVE, the existing school they previously already selected is stored in the database, but now they need to add a few more selected schools. I am not sure if I have to try to load each school to see if it exists.. if it does, then call merge, if not then call persist.. something like:

      public void saveSchools(List<School> schools){
      if (null != schools && schools.size() > 0){
      for(School school : schools){
      School doesItExist = em.find(School.class, school.getId());
      if (null != doesItExist){
      em.merge(school);
      } else {
      em.persist(school);
      }
      }
      }

      Is the above the correct way to store a collection of values some of which may be new, some of which may contain changes to existing data?

      Thank you.