title: Spring MVC + Thymeleaf: Why is the view returning a new object to controller instead of the original one?
body: <p>When I'm updating an object, I send it to the view as a model attribute. But when the view returns it, it comes without the _id (a new object). MongoDB proceeds to create a new object instead of updating an existing one. To avoid this I'm including the id of the object as a hidden input in the view, but that doesn't feel right. Is there another way of achieving this, a more "professional" way? </p>
  
  <pre><code>@Controller
  @RequestMapping("users")
  public class UserController {
      @Autowired
      private UserRepository userRepository;
  
      @GetMapping(value = "/save")
      public String saveUserForm(@RequestParam("id") String id, Model model)
      {           
          User user = userRepository.findById(id).get();
          model.addAttribute("user", user);
          return "saveUser";
      }
      @PostMapping(value = "/save") 
      public String saveUser(@ModelAttribute("user") User user) 
      {
          userRepository.save(user);
          return "redirect:/users";
      }
  }
  
  **********************saveUser.html***************************
  ...
  &lt;form th:method="POST" th:modelAttribute="user" th:action="@{/users/save}" th:id="saveUserForm"&gt;
      &lt;input type="hidden" name ="userId" th:value="${user.userId}"/&gt;
      &lt;label for="name"&gt;Name: &lt;/label&gt;
      &lt;input type="text" name="name"  th:value="${user.name}"/&gt;
      &lt;br /&gt; 
      &lt;label for="creationDate"&gt;Creation: &lt;/label&gt;
      &lt;input type="date" name="creationDate"  th:field="${user.creationDate}"/&gt;
      &lt;br /&gt; 
      &lt;input type="submit" value="Update" /&gt;
  &lt;/form&gt;
  ...
  </code></pre>