Olá boa noite, gostaria de uma ajuda dos senhores, pois já quebrei a cabeça, mas não consegui resolver o problema.
Estou tentando editar um relacionamento de OneToOne, porem ao tentar realizar o processo, o sistema insere um novo registro em vez de realizar o UPDATE na Tabela Profissional, porem a Tabela Usuario é realizado o UPDATE, conforme códigos abaixo.
Segue código para analise!
@Table
@Entity(name = “usuario”)
public class Usuario implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long idUsuario;
@Column(name = "email", nullable = false, unique = true)
private String email;
@Column(name = "senha", nullable = false)
private String senha;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
@Column(name = "dtCadastro")
private LocalDate dtCadastro;
@Enumerated(EnumType.STRING)
@Column(name = "perfil")
private Perfil perfil;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "idProfissional", referencedColumnName = "idProfissional", unique = true)
private Profissional profissional;
@Table
@Entity(name = “profissional”)
public class Profissional implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long idProfissional;
@Column(name = "nome", length = 90)
private String nome;
@Column(name = "sobreNome", length = 90)
private String sobreNome;
@Column(name = "rg", length = 8)
private String rg;
@Column(name = "cpf", length = 13)
private String cpf;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
@Column(name = "dtNascimento")
private LocalDate dtNascimento;
@Enumerated(EnumType.STRING)
@Column(name = "genero")
private Genero genero;
@Column(name = "pcd", length = 4)
private String pcd;
@Embedded
private Endereco endereco;
@OneToOne(mappedBy = "profissional")
private Usuario usuario;
@Repository
public interface Usuarios extends JpaRepository<Usuario, Long>{
@Repository
public interface Profissionals extends JpaRepository<Profissional, Long>{
@Service
@Transactional(readOnly = true)
public class CadastroUsuarioService {
@Autowired
private Usuarios usuarios;
@Transactional(readOnly = false)
public void salvar(Usuario usuario) {
usuario.setPerfil(Perfil.CANDIDATO);
usuario.setDtCadastro(LocalDate.now());
usuarios.save(usuario);
}
}
@Controller
public class UsuarioController {
@Autowired
private Usuarios usuarios;
@Autowired
private CadastroUsuarioService service;
@RequestMapping(value = "/usuario/novo", method = RequestMethod.GET)
public ModelAndView novo(Usuario usuario) {
ModelAndView view = new ModelAndView("usuario/cadastroUsuario");
view.addObject("perfil", Perfil.values());
view.addObject("generos", Genero.values());
return view;
}
@RequestMapping(value = "/usuario/novo", method = RequestMethod.POST)
public ModelAndView cadastrar(@Valid Usuario usuario, BindingResult result, Model model,
RedirectAttributes attributes) {
if (result.hasErrors()) {
return novo(usuario);
}
attributes.addFlashAttribute("message", "Salvo com sucesso!");
service.salvar(usuario);
return new ModelAndView("redirect:/usuario/novo");
}
@RequestMapping(value = "/usuario/todos")
public ModelAndView listaTodos() {
ModelAndView model = new ModelAndView("usuario/pesquisaUsuarios");
model.addObject("listaUsuarios", usuarios.findAll());
return model;
}
@GetMapping(value = "/usuario/delete/{idUsuario}")
public String delete(@PathVariable("idUsuario") Long idUsuario) {
usuarios.delete(idUsuario);
return "redirect:/usuario/todos";
}
@RequestMapping(value = "/usuario/update/{idUsuario}", method = RequestMethod.GET)
public ModelAndView preUpdate(@PathVariable("idUsuario") Long idUsuario) {
ModelAndView view = new ModelAndView();
Usuario usuario = usuarios.findOne(idUsuario);
view.addObject("usuario", usuario);
view.addObject("perfil", Perfil.values());
view.addObject("generos", Genero.values());
view.setViewName("usuario/cadastroUsuario");
return view;
}
}
Hibernate: insert into profissional (cpf, dtNascimento, cep, cidade, complemento, estado, logradouro, numero, genero, nome, pcd, rg, sobreNome, idProfissional) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
00:30:59.294 DEBUG org.hibernate.SQL: update usuario set dtCadastro=?, email=?, perfil=?, idProfissional=?, senha=? where idUsuario=?
Hibernate: update usuario set dtCadastro=?, email=?, perfil=?, idProfissional=?, senha=? where idUsuario=?
Vaga
<div th:each="erro : ${#fields.detailedErrors('${usuario.*}')}">
<span th:text="${erro.message}"></span>
</div>
<form method="POST" th:action="@{/usuario/novo}">
<span th:text="${message}">Erro!</span>
<br>
<fieldset>
<legend>Dados Usuario</legend>
<label for="email">E-mail:</label>
<input id="email" th:required="*{usuario.email}"
type="text" th:field="*{usuario.email}"/>
<br>
<label for="senha">Senha:</label>
<input id="senha" th:required="*{usuario.senha}"
type="text" th:field="*{usuario.senha}"/>
<br>
</fieldset>
<fieldset>
<legend>Dados Pessoais</legend>
<label for="nome">Nome:</label>
<input id="nome" maxlength="90"
type="text" th:field="*{usuario.profissional.nome}"/>
<br>
<label for="sobreNome">SonreNome:</label>
<input id="sobreNome" maxlength="90"
type="text" th:field="*{usuario.profissional.sobreNome}"/>
<br>
<label for="rg">Rg:</label>
<input id="rg" maxlength="8"
type="text" th:field="*{usuario.profissional.rg}"/>
<br>
<label for="cpf">Cpf:</label>
<input id="cpf" maxlength="13"
type="text" th:field="*{usuario.profissional.cpf}"/>
<br>
<label for="dataNasc">Data Nascimento:</label>
<input id="dataNasc" type="date"
th:required="*{usuario.profissional.dtNascimento}" th:field="*{usuario.profissional.dtNascimento}"/>
<br>
<label for="genero">Genero</label>
<select id="genero" th:field="*{usuario.profissional.genero}">
<option value="">Selecione o genero</option>
<option th:each="genero : ${generos}" th:value="${genero}"
th:text="${genero.descricao}">Genero</option>
</select>
<br>
<label for="pcd">Pcd:</label>
<input id="pcd" maxlength="4"
type="text" th:field="*{usuario.profissional.pcd}"/>
<br>
</fieldset>
<input type="hidden" id="idUsuario" th:field="*{usuario.idUsuario}"/>
<button type="submit">Salvar</button>
</form>
Pequisa Usuarios
| Código | Nome | Pefil | AÇÃO | |
|---|---|---|---|---|
| Editar Excluir |