Bom dia!!
Estou desenvolvendo uma aplicação utilizando Spring MVC, porém quando tento gravar a informação no banco está retornando um erro de conversão: Failed to convert value of type ‘java.lang.String’ to required type ‘br.com.ordenador.model.Categoria’; nested exception is org.springframework.core.convert. Porém o tipo do campo que estou tentando gravar é String
Model:
package br.com.ordenador.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotBlank;
@Entity
@Table(name = "tb_categoria")
@SequenceGenerator(name = "categoria_seq", sequenceName = "categoria_seq", initialValue = 1, allocationSize = 1)
public class Categoria {
@Id
@Column(name = "id_categoria")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "categoria_seq")
private short id;
@Column(name = "desc_categoria")
@NotBlank(message = "A descrição da categoria é obrigatória")
@Size(max = 20, message = "A descrição não pode conter mais de 20 caracteres")
private String categoria;
public short getId() {
return id;
}
public void setId(short id) {
this.id = id;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((categoria == null) ? 0 : categoria.hashCode());
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Categoria other = (Categoria) obj;
if (categoria == null) {
if (other.categoria != null)
return false;
} else if (!categoria.equals(other.categoria))
return false;
if (id != other.id)
return false;
return true;
}
}
Controller:
package br.com.ordenador.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.ordenador.model.Categoria;
import br.com.ordenador.repository.filter.CategoriaFilter;
import br.com.ordenador.service.CategoriaService;
@Controller
@RequestMapping("/categorias")
public class CategoriaController {
@Autowired
private CategoriaService categoriaService;
private static final String CADASTRO_VIEW = "categoria/CadastroCategoria";
private static final String PESQUISA_VIEW = "categoria/PesquisaCategoria";
@RequestMapping("/novo")
public ModelAndView novo() {
ModelAndView mv = new ModelAndView(CADASTRO_VIEW);
mv.addObject(new Categoria());
return mv;
}
@RequestMapping(method = RequestMethod.POST)
public String salvar(@Validated Categoria categoria, Errors errors, RedirectAttributes attributes) {
if (errors.hasErrors()) {
return CADASTRO_VIEW;
} else {
categoriaService.salvar(categoria);
attributes.addFlashAttribute("mensagem", "Categoria salva com sucesso!");
return "redirect:/categorias/novo";
}
}
@RequestMapping
public ModelAndView pesquisar(@ModelAttribute("filtro") CategoriaFilter filtro) {
List<Categoria> todasCategorias = categoriaService.filtrar(filtro);
ModelAndView mv = new ModelAndView(PESQUISA_VIEW);
mv.addObject("categorias", todasCategorias);
return mv;
}
@RequestMapping("{id}")
public ModelAndView editar(@PathVariable("id") Categoria categoria) {
ModelAndView mv = new ModelAndView(CADASTRO_VIEW);
mv.addObject(categoria);
return mv;
}
@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
public String excluir(@PathVariable short id, RedirectAttributes attributes) {
categoriaService.excluir(id);
attributes.addFlashAttribute("mensagem", "Categoria excluída com sucesso!");
return "redirect:/categorias";
}
}
Service:
package br.com.ordenador.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.ordenador.model.Categoria;
import br.com.ordenador.repository.Categorias;
import br.com.ordenador.repository.filter.CategoriaFilter;
@Service
public class CategoriaService {
@Autowired
private Categorias categorias;
public void salvar(Categoria categoria) {
categorias.save(categoria);
}
public void excluir(short id) {
categorias.delete(id);
}
public List<Categoria> filtrar(CategoriaFilter filtro) {
String categoria = filtro.getCategoria() == null ? "%" : filtro.getCategoria();
return categorias.findByCategoriaContainingIgnoreCaseOrderById(categoria);
}
}
HTML:
Cadastro de categoria
<div class="panel panel-default">
<div class="panel-heading">
<div class="clearfix">
<h1 class="panel-title aw-titulo-panel">Cadastrar categoria</h1>
<a class="btn btn-link aw-link-panel" th:href="@{/categorias}">Pesquisar</a>
</div>
</div>
<input type="hidden" th:field="*{id}" />
<div class="panel-body">
<div class="form-group" th:classappend="${#fields.hasErrors('categoria')} ? has-error">
<label for="desc_categoria" class="col-sm-2 control-label">Categoria</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="desc_categoria" autofocus="autofocus" th:field="*{categoria}" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Salvar</button>
</div>
</div>
</div>
</div>
</form>
</section>
</html>
Mensagem de erro:
2017-06-28 11:06:19.273 WARN 4972 — [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to bind request element: org.springframework.beans.TypeMismatchException: Failed to convert value of type ‘java.lang.String’ to required type ‘br.com.ordenador.model.Categoria’; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Short] for value ‘Família’; nested exception is java.lang.NumberFormatException: For input string: “Família”
2017-06-28 11:06:19.274 WARN 4972 — [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.beans.TypeMismatchException: Failed to convert value of type ‘java.lang.String’ to required type ‘br.com.ordenador.model.Categoria’; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Short] for value ‘Família’; nested exception is java.lang.NumberFormatException: For input string: “Família”
Alguém consegue ver onde está meu erro?