title: Hibernate: update instead insert
body: <p>I have entity:</p>
  
  <pre><code>@Entity
  @Table(name = "users")
  public class User {
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private int id;
  
      @Column(name = "name", nullable = false)
      private String name;
  
   @OneToMany(fetch = FetchType.LAZY, mappedBy = "parentid", cascade=CascadeType.ALL)
      private List&lt;Lesson&gt; lessonList = new ArrayList&lt;&gt;();
  ....setters/getters
  }
  </code></pre>
  
  <p>I get user from BD and do xml:</p>
  
  <pre><code>&lt;user&gt;
  
          &lt;name&gt;123&lt;/name&gt;
  
          &lt;id&gt;35&lt;/id&gt;
  
  &lt;/user&gt;
  </code></pre>
  
  <p>Next I get new User from this xml and try to save in BD.</p>
  
  <pre><code>session.save(user);
  </code></pre>
  
  <p>If list lessonList of user is empty Hibernate inserts NEW user in BD. If list is not empty Hibernate uses update. Why?</p>
  
  <p>I use JAXB</p>
  
  <pre><code>User.class
  
       @Entity
          @Table(name = "users")
          public class User {
              @Id
              @GeneratedValue(strategy = GenerationType.AUTO)
              private int id;
  
              @Column(name = "name", nullable = false)
              private String name;
  
           @OneToMany(fetch = FetchType.LAZY, mappedBy = "parentid", cascade=CascadeType.ALL)
              private List&lt;Lesson&gt; lessonList = new ArrayList&lt;&gt;();
          ....setters/getters
          }
  </code></pre>
  
  <p>create XML with JAXB</p>
  
  <pre><code>@Transactional
      public User getUserFromXML(int id) {
         StringWriter stringWriter = new StringWriter();
         User copyUser = null;
          User user = UserDAO.getById(id);
          try {
              JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
              Marshaller marshaller = jaxbContext.createMarshaller();
              marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
              marshaller.marshal(user, stringWriter);
              StringReader stringReader = new ringReader(stringWriter.toString());
              Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
              copyUser = (User) unmarshaller.unmarshal(stringReader);
              } catch (JAXBException e) {
              e.printStackTrace();
          }
          return copyUser;
  }
  </code></pre>
  
  <p>controller:</p>
  
  <pre><code> @Transactional
      void copyUser(HttpServletRequest request, HttpServletResponse response) {
  
                  User copyUser = getUserFromXML(idUser);// it get from Client
                  copyUser.setParentid(getLoginUser());
                  userDAO.save(copyUser);
  
          }
      }
  </code></pre>