Ola, por algum motivo o hibernate está tentando fazer um insert quando estou tentado atualizar algum registro, vi alguns exemplos e não entendi o que estou fazendo de errado.
Meu modelo:
@Entity public class Funcionario { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String matricula; private String nome;
A classe do DAO:
@Repository
@Transactional
public class FuncionarioDAO {
@PersistenceContext
private EntityManager manager;
public void save(Funcionario funcionario){
manager.persist(funcionario);
}
public List<Funcionario> findAll() {
return manager.createQuery("select f from Funcionario f", Funcionario.class).getResultList();
}
public Funcionario find(String matricula) {
return manager.createQuery("select distinct(f) from Funcionario f where f.matricula = :matricula", Funcionario.class).setParameter("matricula", matricula).getSingleResult();
}
}
Meu controlador
@Controller
@RequestMapping("rhm/funcionario")
public class FuncionarioController {
@Autowired
private FuncionarioDAO funcionarioDAO;
@RequestMapping("/{matricula}")`
public ModelAndView edit(@PathVariable("matricula") String matricula){
ModelAndView modelAndView = new ModelAndView("/rhm/funcionarioUpdate");
Funcionario funcionario = funcionarioDAO.find(matricula);
modelAndView.addObject("funcionario", funcionario);
return modelAndView;
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(MultipartFile fotoPath ,@Valid Funcionario funcionario, BindingResult result, RedirectAttributes redirectAttributes) {
if(result.hasErrors()) {
redirectAttributes.addFlashAttribute("message", "Erro ao salvar funcionário");
if(!funcionario.getMatricula().isEmpty()) {
return edit(funcionario.getMatricula());
}
return add(funcionario);
}
if(!fotoPath.isEmpty()) {
String path = fileSaver.write("fotos", fotoPath);
funcionario.setFoto(path);
}
funcionarioDAO.save(funcionario);
redirectAttributes.addFlashAttribute("message", "Funcionário cadastrado com Sucesso");
return new ModelAndView("redirect:/rhm/funcionario/all");
}
Meu form está assim:
<form action="/dome/rhm/funcionario/save" method="post" enctype="multipart/form-data">
Matrícula*
<form:input path="funcionario.matricula" />
<form:hidden path="funcionario.id" />
Nome* <form:input path="funcionario.nome" />
Nascimento <input type="date" name="dtaNascimento" />
Foto <input type="file" name="fotoPath" />
</form>
Para criar novo registro vai normal, quando tento atualizar um registro:
GRAVE: Servlet.service() for servlet [dispatcher] in context with path [/dome] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: br.com.dome.model.Funcionario] with root cause