title: Spring MVC complex object data binding
body: <p>I am still struggling with Spring MVC with what should be a fairly straightforward problem but what seems to be sparsly documented in Spring MVC documentation.</p>
  
  <p>My project uses Spring MVC and Thymeleaf for the views, but the view rendering engine is not really relevant to the problem.</p>
  
  <p>My application is centered around an Activity class which models an (indoor or outdoor) activity which is organized by a member and where fellow members can subscribe to. An Activity has, among others, a Category field and a Region field, which are dropdown fields which are modeled by Hibernate as many-to-one entities to DB lookup tables which contain an id and description field.</p>
  
  <p>The code for the Activity entity class is as follows, the non relevant fields are omitted to shorten the code:</p>
  
  <pre><code>package nl.drsklaus.activiteitensite.model;
  
  //imports
  
  @Entity
  @Table(name="activity")
  public class Activity {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY) 
  private Integer id;
  
  @ManyToOne(cascade=CascadeType.ALL)
  @JoinColumn(name="organizer_id")
  private Member organizer;
  
  @Size(min=5, max=50)
  @Column(name = "title", nullable = false)
  private String title;
  
  @Size(min=5, max=500)
  @Column(name = "description", nullable = false)
  private String description;
  
  @ManyToOne
  @JoinColumn(name="category_id")
  private ActivityCategory category;
  
  @ManyToOne
  @JoinColumn(name="region_id")
  private ActivityRegion region;
  
  
  @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  @JoinTable(name="member_activity_subscription", 
             joinColumns = {@JoinColumn(name="activity_id")}, 
             inverseJoinColumns={@JoinColumn(name="member_id")})
  private List&lt;Member&gt; participants = new ArrayList&lt;Member&gt;();
  
  //getters and setters   
  
  @Override
  public int hashCode() {
    ...
  }
  
  @Override
  public boolean equals(Object obj) {
    ...
  }
  }
  </code></pre>
  
  <p>In the view, the user should be able to select a Region and Category from a select box. THe options are put in the Model using a @ModelAttribute annotated method on the class level.</p>
  
  <p>THe problem is with the binding of the  box to the lookup property fields. </p>
  
  <p>For example the Category field is of the ActivityCategory type, which is an entity class containing an id and a description property.</p>
  
  <p>In the view, the select box is filled with the list of possible options (allCategories which contains ActivityCategory instances), Thymeleaf takes care of selecting the current value by matching the "value" attribute value with the list:</p>
  
  <pre><code>&lt;label&gt;Categorie&lt;/label&gt;
  &lt;select th:field="*{category}"&gt;
    &lt;option th:each="cat : ${allCategories}"
            th:value="${cat}"
            th:text="${cat.description}"&gt;
    &lt;/option&gt;
  &lt;/select&gt;
  </code></pre>
  
  <p>The generated HTML looks like:</p>
  
  <pre><code>&lt;select id="category" name="category"&gt;
        &lt;option value="nl.drsklaus.activiteitensite.model.lookup.ActivityCategory@20"&gt;Actief en sportief&lt;/option&gt;
        &lt;option value="nl.drsklaus.activiteitensite.model.lookup.ActivityCategory@21"&gt;Uitgaan en nachtleven&lt;/option&gt;
        &lt;option value="nl.drsklaus.activiteitensite.model.lookup.ActivityCategory@22" selected="selected"&gt;Kunst en cultuur&lt;/option&gt;
        &lt;option value="nl.drsklaus.activiteitensite.model.lookup.ActivityCategory@23"&gt;Eten en drinken&lt;/option&gt;
        &lt;option value="nl.drsklaus.activiteitensite.model.lookup.ActivityCategory@24" selected="selected"&gt;Ontspanning en gezelligheid&lt;/option&gt;
  &lt;/select&gt;
  </code></pre>
  
  <p>As we see, the value attributes contain a string representation of the object itself which is clearly not desired, to show the id values we could use ${cat.id} instead of ${cat} but then the selection of the current value (setting the 'selected="selected"' attribute) does not work anymore. THerefore I implemented a Converter which converts an ActivityCategory object to an int (the id value). In Thymeleaf, the converter is called by using the double accolades {{}}:</p>
  
  <pre><code>th:value="${{cat}}"
  </code></pre>
  
  <p>THe converter is created and added to Spring:</p>
  
  <pre><code>public class LookupConverter implements Converter&lt;LookupEntity, String&gt; {
    public String convert(LookupEntity source) {
       return String.valueOf(source.getId());
    }
  }
  </code></pre>
  
  <p>//In MvcConfig class</p>
  
  <pre><code>@Override
  public void addFormatters(FormatterRegistry registry) {
    registry.addConverter(new LookupConverter());
  }
  </code></pre>
  
  <p>Now the HTML shows the id values for the options, which is much more logical:</p>
  
  <pre><code>&lt;select id="category" name="category"&gt;
        &lt;option value="1"&gt;Actief en sportief&lt;/option&gt;
        &lt;option value="2"&gt;Uitgaan en nachtleven&lt;/option&gt;
        &lt;option value="3" selected="selected"&gt;Kunst en cultuur&lt;/option&gt;
        &lt;option value="4"&gt;Eten en drinken&lt;/option&gt;
        &lt;option value="5"&gt;Ontspanning en gezelligheid&lt;/option&gt;
  &lt;/select&gt;
  </code></pre>
  
  <p>But it still wrong after submitting, the id value cannot be bound to the Activity object which expects a ActivityCategory instead if an integer value, so a typeMismatch validation error is generated.</p>
  
  <p>My handler method looks like:</p>
  
  <pre><code>@RequestMapping(value = "/{id}/submit", method = RequestMethod.POST)
  public String submitForm(@ModelAttribute("activity") Activity activity, BindingResult result, ModelMap model) {
  
      if (result.hasErrors()) {
          return "activityform";
      } else {
  
          if (activity.getId() == null) {
              this.service.saveActivity(activity);
          } else {
              this.service.mergeWithExistingAndUpdate(activity);
          }
  
          return "redirect:/activity/" + activity.getId() + "/detail";
      }
  }
  </code></pre>
  
  <p>I have looked at many posts but still found have no solution for this IMHO pretty trivial issue. How can the String value containing the id be accepted by the handler method and properly converted? Or can we not use the id value for this purpose? 
  Looking for some hints...</p>