Problem in persistence of data using JPA

2

I have a class that has two attributes, start time and end time, both of type Date.

@Temporal(TemporalType.TIME)
private Date horarioInicio;
@Temporal(TemporalType.TIME)
private Date horarioFinal;

In the view layer the Spring Data Binding feature is being used, but when I submit the form with the data, I have the 400 status code as a return, indicating that there is a problem with the request. When both fields are removed, the form is submitted normally. Remembering that the command object is already part of the view.

<div class="form-group col-md-2">
    <form:label path="horarioInicio">Horario inicio</form:label>
    <form:input id="horarioInicio" path="horarioInicio" class="form-control input-sm" type="time" />
</div>

<div class="form-group col-md-2">
    <form:label path="horarioFinal">Horario final</form:label>
    <form:input id="horarioFinal" path="horarioFinal" class="form-control input-sm" type="time" />
</div>

Controller

@RequestMapping("/salvarManutencao")
public String saveFornecedor(@ModelAttribute("manutencao") Manutencao manutencao,
        @ModelAttribute("produtosManutencao") HashMap<Long, Long> produtosManutencao, BindingResult bindingResult) {

    if (bindingResult.hasErrors())
        return "/manutencao/save/saveManutencao";

    manutencaoService.saveManutencao(manutencao, produtosManutencao);
    return "redirect:fornecedores";
}

Both attributes are part of the Maintenance class.

Has anyone ever had anything similar?

    
asked by anonymous 10.06.2017 / 20:30

1 answer

1

You have 2 errors, the first is your BindingResult that should be declared as parameter after the object to be validated, as it is, it will validate only produtosManutencao

Do this:

@RequestMapping("/salvarManutencao")
public String saveFornecedor(
        @ModelAttribute("manutencao") Manutencao manutencao,
        BindingResult bindingResult,
        @ModelAttribute("produtosManutencao") HashMap<Long, Long> produtosManutencao
) {

    if (bindingResult.hasErrors())
        return "/manutencao/save/saveManutencao";

    manutencaoService.saveManutencao(manutencao, produtosManutencao);
    return "redirect:fornecedores";
}

Placing the bindingResult after @ModelAttribute("manutencao") Manutencao manutencao it will validate correctly, not only displaying the error 400 (bad request)

After this you will get another error, but this time why Spring could not handle the date format.

To resolve the second problem, you must enter the date pattern as follows:

@DateTimeFormat(pattern = "hh:mm")
@Temporal(TemporalType.TIME)
private Date horarioInicio;

@DateTimeFormat(pattern = "hh:mm")
@Temporal(TemporalType.TIME)
private Date horarioFinal;
    
10.06.2017 / 23:31