Data persistence problem using JPA

Asked

Viewed 121 times

2

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

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

In the display layer is being used the Spring Data Binding feature, but when submitting the form with the data, I return the status code 400, indicating that there is some problem in the request. When the two fields are removed, the form is normally submitted. Remember 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.

Someone’s been through something similar?

1 answer

1


You have 2 mistakes, the first one is yours BindingResult which must be declared as a parameter after the object to be validated, as it is, will validate only produtosManutencao

Do so:

@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";
}

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

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

To solve the second problem, you will need to inform the date pattern, so:

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

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

Browser other questions tagged

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