Spring’s Bind with Collections

Asked

Viewed 60 times

0

I haven’t been able to find a solution on how to resolve this issue yet, after researching and researching I found something on how I can bind elements of my form to a Collection in a POJO. But first I would like to explain the business rule of the module in which I am developing to help the reader to orient, then even indicate me another solution if it is necessary.

I have a form in which I can register "travel passengers" and later popular a table for when it is submitted to Collection to be persisted in bank. Below the image for easy viewing:

inserir a descrição da imagem aqui

Soon I created my Entity of Customer in which will contain a Set of passengers:

Customer Java.

@Entity
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_customer")
    private Long idCustomer;

    @Column(name="birth_date")
    @DateTimeFormat(pattern = "dd/MM/yyyy")
    @Temporal(TemporalType.DATE)
    private Date birthDate;

    @Column(name="email")
    private String email;

    @Column(name="first_name")
    private String firstName;

    @Column(name="gender")
    private String gender;

    @Column(name="last_name")
    private String lastName;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_document")
    private Document document;


    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_customerPhone")
    private CustomerPhone customerPhone;


    @OneToMany(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_customer")
    private Set<Passenger> passenger = new HashSet<Passenger>();

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_customerAddress")
    private CustomerAddress customerAddress;


    public Customer() {
    }
    //Getters and Setters
}

Passenger java.

@Entity
public class Passenger implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_passengers")
    private Long id;

    @Column(name="birth_date")
    private String birthDate;

    @Column(name="p_email")
    private String email;

    @Column(name="p_first_name")
    private String firstName;

    @Column(name="p_last_name")
    private String lastName;

    @Column(name="main_tel")
    private String mainTel;


    @Enumerated(EnumType.STRING)
    @Column(name="family_bond")
    private FamilyBond familyBond;


    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_documentPassenger")
    private DocumentPassenger documentPassenger;


    public Passenger() {
    }
    //Getter and Setter

}

My controller:

@Controller
@Transactional(propagation = Propagation.REQUIRED)
@RequestMapping("/auth")
public class CustomerController {

    @Autowired
    public CustomerFacade customerFacade;

    @RequestMapping("/customer")
    public ModelAndView getMenuService(Model model){
        List<Country> countriesList = customerFacade.getCountriesList();    
        model.addAttribute("countriesList", countriesList);

        return new ModelAndView("customer/newCustomer", "customer", new Customer());
    }

Well, now that the bug catches! Because I want to perform the bind of Collection with some components inside my form in the view.

After searching a bit I ended up finding this approach:

<f:form id="transition-duration-demo" class="transition-form" modelAttribute="customer" method="post">
   <div class="aling-form col-sm-12 nest text" style="padding-top:25px">
   <c:forEach items="${customer.passenger}" var="passenger" varStatus="status">

   <div class="box02">
      <f:input id="passenger-name" placeholder="Nome do Passageiro" type="text" path="passenger[${status.index}].firstName" class="form-control"/>
   </div>
   <!--Continua-->
</f:form>

Well, the components don’t show up on the screen, but I think it’s because my list is null!

Can anyone help me with this question is I doing it the right way? Has anyone ever used the Autopopulatinglist of Spring and can give me some information?

  • 1

    John, let me get this straight. You have a modal with a form. By "submitting" that form you want it to feed a table on the main page. When the main page table is submitted you want to send an entire Collection (with all passengers registered through the form) to be persisted on the server side. That’s it?

  • So @Anthonyaccioly and almost that. I actually have one form in which the elements of my modal belong to him. When my user enters the data in the modal some fields go to the table on the main screen (this is only for reference if the user wants to delete some object). So when my data form (including modal data) be filled in I perform Submit. I have my entity Customer.java in which there is a Set of Passenger.java (precisely the fields that are in the modal). But the problem is to perform the bind with Collections.

1 answer

1


Well, after the help of a friend of the GUJ forum and a little research I came to the conclusion that to popular my list would have the possibility d do by two ways, AJAX or removing my modal from mine form main and creating another form calling an action in my controller and thus populating a List.

I chose to do it by submitting a separate form, as I don’t have much intimacy with AJAX calls yet. Below follows the implementation:

Close-up Register New Passenger

            <div class="aling-form col-sm-12 nest text" style="padding-top:25px">           

                <div class="box01">
                    <select id="familyBond" class="form-control" name="familyBond">
                        <option value="null" label="-- Vinculo do Passageiro --" />
                        <c:forEach items="${listOfBondNames}" var="bond">
                            <option value="">${bond.value}</option>
                        </c:forEach>
                    </select>
                </div>

                    <div class="box02">
                        <input id="passenger-name" placeholder="Nome do Passageiro" name="firstName" type="text" class="form-control"/>
                    </div>

                    <div class="box01">
                        <input id="passenger-lastName" placeholder="Sobrenome do Passageiro" type="text" name="lastName" class="form-control"/>
                    </div>

                    <div class="box02">
                        <div class="input-group ">
                            <span class="input-group-addon btn-success"><i class="fa fontawesome-envelope-alt"></i></span>
                            <input id="passenger-email" placeholder="E-mail" type="text"  name="email" class="form-control"/>
                        </div>
                    </div>

                    <div class="box01">
                        <div class="input-group ">
                            <span class="input-group-addon btn-success"><i class="fa fa-phone-square"></i></span>
                            <input id="passenger-phone" placeholder="Telefone Principal" type="text" name="mainTel" class="form-control"/>
                        </div>
                    </div>

                    <div class="box02">
                        <div class="input-group ">
                            <span class="input-group-addon btn-success"><i class="fa fa-calendar"></i></span>
                            <input id="passenger-birth" placeholder="Data de Nascimento" type="text" name="birthDate" class="form-control"/>
                        </div>
                    </div>

                    <div class="box01">
                        <input id="passenger-rg" placeholder="RG" type="text" name="documentPassenger.rg" class="form-control" style="margin:0px;"/>
                    </div>

                    <div class="box02">
                        <input id="passenger-cpf" placeholder="CPF" type="text" name="documentPassenger.cpf" class="form-control"/>
                    </div>
                    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

                </div>

          </div>
          <div class="modal-footer clear" style="margin:0px;">
            <button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
            <button type="submit" class="btn btn-primary">Cadastrar</button>
          </div>
          </form>
        </div>
      </div>
    </div>

Soon he calls the action:

private List<Passenger> passengerList = new ArrayList<Passenger>();

    @RequestMapping(value="/addPassenger", method=RequestMethod.POST)
    public ModelAndView addPassenger(Passenger passenger, Model model){
        passengerList.add(passenger);

        ModelAndView mv = new ModelAndView("service/newService");
        mv.addObject("passengerList", passengerList);
        mv.addObject("customer", new Customer());
        initializeComponents(model);
       return mv;
    }

With this approach I have my passengerList populated for when submitting my main form I apanes set the list in bean.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.