title: Spring form:select multiple selected value?
body: <p>I have this edit form:</p>
  
  <p><img src="https://i.stack.imgur.com/0JJsQ.png" alt="enter image description here"></p>
  
  <p>I want that the roles of the user get selected. If this were one-to-many relation I know that I can do something like this:</p>
  
  <pre><code>        &lt;form:label path="roles"&gt;Roles:&lt;/form:label&gt;
          &lt;form:select multiple="true" path="roles"&gt;
              &lt;c:forEach items="${roles}" var="rol"&gt;
                  &lt;c:choose&gt;
                      &lt;c:when
                          test="${usuarioEdit.rol.id ==rol.id}"&gt;
                          &lt;option value="${rol.id}" selected="selected"&gt;${rol.nombre}&lt;/option&gt;
                      &lt;/c:when&gt;
                      &lt;c:otherwise&gt;
                          &lt;option value="${rol.id}"&gt;${rol.nombre}&lt;/option&gt;
                      &lt;/c:otherwise&gt;
                  &lt;/c:choose&gt;
  
              &lt;/c:forEach&gt;
          &lt;/form:select&gt;
          &lt;form:errors cssStyle="color:red" path="roles"&gt;&lt;/form:errors&gt;
  </code></pre>
  
  <p>But this is a many-to-many relation. How can I get selected the options in an edit form?. Is there an easy form? </p>
  
  <p>This code works, but I wonder if spring gives any facilities:</p>
  
  <pre><code>&lt;form:select multiple="true" path="roles"&gt;
              &lt;c:forEach items="${roles}" var="rol"&gt;
                  &lt;c:set var="isSelected" value="false" /&gt;
                  &lt;c:forEach items="${rolesUsu}" var="rolUsu"&gt;
                      &lt;c:if test="${rolUsu.getRol().getId()==rol.id}"&gt;
                          &lt;c:set var="isSelected" value="true" /&gt;
                      &lt;/c:if&gt;
                  &lt;/c:forEach&gt;
                  &lt;c:choose&gt;
                      &lt;c:when test="${isSelected}"&gt;
                          &lt;option value="${rol.id}" selected="selected"&gt;${rol.nombre}&lt;/option&gt;
                      &lt;/c:when&gt;
                      &lt;c:otherwise&gt;
                          &lt;option value="${rol.id}"&gt;${rol.nombre}&lt;/option&gt;
                      &lt;/c:otherwise&gt;
                  &lt;/c:choose&gt;
              &lt;/c:forEach&gt;
          &lt;/form:select&gt;
  </code></pre>
  
  <p><strong>Edit:</strong> </p>
  
  <p>In my controller I have:</p>
  
  <pre><code>@InitBinder
      public void initBinder(WebDataBinder binder) {
  
          binder.registerCustomEditor(Set.class, "roles",
                  new RolCollectionEditor(Set.class, rolDao));
  
      }
  </code></pre>
  
  <p>RolCollectionEditor:</p>
  
  <pre><code>public class RolCollectionEditor extends CustomCollectionEditor {
  
       private final RolDAO rolDao;
  
  
      public RolCollectionEditor(Class&lt;?&gt; collectionType, RolDAO rolDao) {
  
          super(collectionType);
          this.rolDao = rolDao;
  
      }
  
      @Override
      protected Object convertElement(Object element) {
          String rolId = (String) element;
  
          Rol rol = rolDao.findById(rolId);
          Usuario_Rol usuRol = new Usuario_Rol();
  
          //Agregamos un usuario vacio temporal
          //y lo sobreescribimos en el controlador
          Usuario usuario = new Usuario();
  
          usuRol.setUsuario(usuario);
          usuRol.setRol(rol);
          usuRol.setFechaCreacion(new Date());
          usuRol.setFechaModificacion(new Date());
          usuRol.setStatus("activo");
  
          return usuRol;
      }
  
  }
  </code></pre>
  
  <p>Here Usuario_Rol is an intermediate table for the many to many relation, that have other attributes besides the userId and rolId. </p>
  
  <p><strong>Edit2:</strong></p>
  
  <p>Rol class:</p>
  
  <pre><code>@Entity
  @Table(name = "rol", uniqueConstraints = { @UniqueConstraint(columnNames = "nombre") })
  public class Rol implements Serializable{
  
      @Id
      @Column(name = "_id")
      private String id;
  
      @Column(name = "nombre")
      @NotNull
      private String nombre;
  
      @Column(name = "descripcion")
      private String descripcion;
  
      @Column(name = "status")
      private String status;
  
      @Column(name = "fechaCreacion")
      private Date fechaCreacion;
  
      @Column(name = "fechaModificacion")
      private Date fechaModificacion;
  
      @Column(name = "fechaSincronizacion")
      private Date fechaSincronizacion;
  
      @OneToMany(fetch = FetchType.EAGER, mappedBy = "usuarioRol_pk.rol", orphanRemoval = true, cascade=CascadeType.ALL)
      private Set&lt;Usuario_Rol&gt; usuarios = new HashSet&lt;Usuario_Rol&gt;(0);
  
  
      //getters and setters
  
      @Override
      final public int hashCode() {
          final int prime = 31;
          int result = 1;
          result = prime * result + ((nombre == null) ? 0 : nombre.hashCode());
          return result;
      }
  
      @Override
      final public boolean equals(Object obj) {
          if (this == obj)
              return true;
          if (obj == null)
              return false;
          if (!(obj instanceof Rol))
              return false;
          Rol other = (Rol) obj;
          if (nombre == null) {
              if (other.nombre != null)
                  return false;
          } else if (!nombre.equals(other.nombre))
              return false;
          return true;
      }
  </code></pre>
  
  <p>Class Usuario:</p>
  
  <p>@Entity
  @Table(name = "usuario", uniqueConstraints = {
          @UniqueConstraint(columnNames = "login"),
          @UniqueConstraint(columnNames = "correo") })
  public class Usuario implements Serializable {</p>
  
  <pre><code>@Id
  @Column(name = "_id")
  private String id;
  
  @Column(name = "nombre")
  @NotEmpty
  private String nombre;
  
  @Column(name = "apellido")
  @NotEmpty
  private String apellido;
  
  @Column(name = "login")
  @Size(min = 4)
  @NotEmpty
  private String login;
  
  @Column(name = "password")
  @NotEmpty
  @Size(min = 4)
  private String password;
  
  @Column(name = "salt")
  private String salt;
  
  @Column(name = "correo")
  @NotEmpty
  @Email
  private String correo;
  
  @Column(name = "token")
  private String token;
  
  @Column(name = "status")
  private String status;
  
  @Column(name = "fechaUltimoLogin")
  private Date fechaUltimoLogin;
  
  @Column(name = "fechaCreacion")
  private Date fechaCreacion;
  
  @Column(name = "fechaModificacion")
  private Date fechaModificacion;
  
  @Column(name = "fechaSincronizacion")
  private Date fechaSincronizacion;
  
  @NotEmpty
  @OneToMany(fetch = FetchType.EAGER, mappedBy = "usuarioRol_pk.usuario", orphanRemoval = true, cascade = CascadeType.ALL)
  private Set&lt;Usuario_Rol&gt; roles = new HashSet&lt;Usuario_Rol&gt;(0);
  
  
  //constructor, getters and setters.
  
  @Override
  final public int hashCode() {
      final int prime = 31;
      int result = 1;
      result = prime * result + ((login == null) ? 0 : login.hashCode());
      return result;
  }
  
  @Override
  final public boolean equals(Object obj) {
      if (this == obj)
          return true;
      if (obj == null)
          return false;
      if (!(obj instanceof Usuario))
          return false;
      Usuario other = (Usuario) obj;
      if (login == null) {
          if (other.login != null)
              return false;
      } else if (!login.equals(other.login))
          return false;
      return true;
  }
  </code></pre>
  
  <p>Intermediate class:</p>
  
  <pre><code>@Entity
  @Table(name = "usuario_rol")
  @AssociationOverrides({
      @AssociationOverride(name = "usuarioRol_pk.usuario", joinColumns = @JoinColumn(name = "idUsuario")),
      @AssociationOverride(name = "usuarioRol_pk.rol", joinColumns = @JoinColumn(name = "idRol")) 
  })
  public class Usuario_Rol implements Serializable{
  
      @EmbeddedId
      private Usuario_RolId usuarioRol_pk = new Usuario_RolId();
  
      @Temporal(TemporalType.DATE)
      @Column(name = "fechaCreacion")
      private Date fechaCreacion;
  
      @Temporal(TemporalType.DATE)
      @Column(name = "fechaModificacion")
      private Date fechaModificacion;
  
      @Temporal(TemporalType.DATE)
      @Column(name = "fechaSincronizacion")
      private Date fechaSincronizacion;
  
      @Column(name = "status")
      private String status;
  
      //gettters, setters
  
      @Override
      final public int hashCode() {
          final int prime = 31;
          int result = 1;
          result = prime * result + ((usuarioRol_pk == null) ? 0 : usuarioRol_pk.hashCode());
          return result;
      }
  
  
      @Override
      final public boolean equals(Object obj) {
          if (this == obj)
              return true;
          if (obj == null)
              return false;
          if (!(obj instanceof Usuario_Rol))
              return false;
          Usuario_Rol other = (Usuario_Rol) obj;
          if (usuarioRol_pk == null) {
              if (other.usuarioRol_pk != null)
                  return false;
          } else if (!usuarioRol_pk.equals(other.usuarioRol_pk))
              return false;
          return true;
      }
  </code></pre>
  
  <p>Usuario_RolId:</p>
  
  <pre><code>@Embeddable
  public class Usuario_RolId implements Serializable{
  
      @ManyToOne
      private Usuario usuario;
  
      @ManyToOne
      private Rol rol;
  
      public Usuario getUsuario() {
          return usuario;
      }
      public void setUsuario(Usuario usuario) {
          this.usuario = usuario;
      }
      public Rol getRol() {
          return rol;
      }
      public void setRol(Rol rol) {
          this.rol = rol;
      }
  
  
      @Override
      final public int hashCode() {
          final int prime = 31;
          int result = 1;
          result = prime * result + ((rol == null) ? 0 : rol.hashCode());
          result = prime * result + ((usuario == null) ? 0 : usuario.hashCode());
          return result;
      }
  
      @Override
      final public boolean equals(Object obj) {
          if (this == obj)
              return true;
          if (obj == null)
              return false;
          if (!(obj instanceof Usuario_RolId))
              return false;
          Usuario_RolId other = (Usuario_RolId) obj;
          if (rol == null) {
              if (other.rol != null)
                  return false;
          } else if (!rol.equals(other.rol))
              return false;
          if (usuario == null) {
              if (other.usuario != null)
                  return false;
          } else if (!usuario.equals(other.usuario))
              return false;
          return true;
      } 
  </code></pre>
  
  <p>This last class is used for the trick of simulating a many to many relation. I have followed this tutorial: <a href="http://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/" rel="nofollow noreferrer">http://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/</a></p>