0
I implemented spring security in my project, I can already register new users and login/logout. Now I’m trying to edit this user’s data, when I click save, it duplicates the data in the database, and as my redirect is to page "My account" it finds two records of the same "username" and returns the error below:
javax.persistence.Nonuniqueresultexception: query Did not Return a Unique result: 2
Follows code:
Repositoryusuario:
public interface RepositoryUsuario extends JpaRepository<Usuario, Long>{
Usuario findByEmail(String email);
Usuario findByUsername(String username);
}
Servicousuario:
@Service
public class ServiceUsuario {
@Autowired
private RepositoryUsuario repUsuario;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
public Usuario encontrarPorUsername(String Username) {
return repUsuario.findByUsername(Username);
}
public void salvar(Usuario usuario) {
usuario.setSenha(passwordEncoder.encode(usuario.getSenha()));
repUsuario.save(usuario);
}
public Usuario getOne(Long id) {
return repUsuario.getOne(id);
}
User:
@Entity
@Table(name = "usuario")
public class Usuario {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "nome", nullable = false, length = 50)
@NotNull(message = "O nome é obrigatório!")
@Length(min = 3, max = 200, message = "O nome deve conter entre 3 a 50 caracteres!")
private String nome;
@Column(name = "sobrenome", nullable = false, length = 100)
@NotNull(message = "O sobrenome é obrigatório!")
@Length(min = 3, max = 100, message = "O sobrenome deve conter entre 3 a 100 caracteres!")
private String sobrenome;
@Column(name = "email", nullable = false, length = 200)
@NotNull(message = "O e-mail é obrigatório!")
@Length(min = 5, max = 200, message = "O e-mail deve conter entre 5 e 200 caracteres!")
private String email;
@Column(name = "senha", nullable = false, length = 20)
@NotNull(message = "A senha é obrigatória!")
private String senha;
@Column(name = "username", nullable = false, length = 20)
@NotNull(message = "O nome de usuário é obrigatório!")
@Length(max = 20, message = "O usuário deve conter entre 5 à 20
caracteres!")
private String username;
@OneToMany(mappedBy = "usuario")
private List<Receita> receita;
@OneToMany(mappedBy = "usuario")
private List<Comentario> comentario;
//Getters e setters
User controller:
@Controller
@RequestMapping("/usuario")
public class UsuarioController {
@Autowired
private ServiceUsuario serviceUsuario;
@Autowired
private RepositoryUsuario repUsuario;
@GetMapping("/minhaConta")
public ModelAndView minhaConta(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("usuario/minhaConta");
String username = request.getUserPrincipal().getName();
Usuario usuario = serviceUsuario.encontrarPorUsername(username);
mv.addObject("usuario", usuario);
return mv;
}
@GetMapping("/alterar/{id}")
public String alterar(@PathVariable("id") Long id, Model model) {
Usuario usuario = serviceUsuario.getOne(id);
model.addAttribute("usuario", usuario);
return "usuario/editarConta";
}
@PostMapping("/alterar")
public ModelAndView alterar(@Valid Usuario usuario, BindingResult result) {
ModelAndView mv = new ModelAndView();
if (result.hasErrors()) {
System.out.println(result.getAllErrors());
mv.setViewName("usuario/editarConta");
mv.addObject(usuario);
} else {
mv.setViewName("redirect:/usuario/minhaConta");
repUsuario.save(usuario);
}
return mv;
}
Editing form:
<h1 class="tituloRegist">Editar dados da conta:</h1>
<div class="divRegist">
<form class="form-horizontal formRegist" action="/usuario/alterar" method="POST" th:object="${usuario}">
<input type="hidden" th:field="*{id}">
<div class="form-group">
<label for="inputNome">Nome</label>
<input type="text" class="form-control" id="inputNome" placeholder="Nome" th:field="*{nome}">
<label th:if="${#fields.hasErrors('nome')}" th:errors="*{nome}" class="validation-message"></label>
</div>
<div class="form-group">
<label for="inputSobrenome">Sobrenome</label>
<input type="text" class="form-control" id="inputSobrenome" placeholder="Sobrenome" th:field="*{sobrenome}">
<label th:if="${#fields.hasErrors('sobrenome')}" th:errors="*{sobrenome}" class="validation-message"></label>
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="text" class="form-control" id="inputEmail" placeholder="Email" th:field="*{email}">
<label th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="validation-message"></label>
</div>
<input type="hidden" th:field="*{senha}">
<input type="hidden" th:field="*{username}">
<button type="submit" class="btn btn-primary">Salvar</button>
</form>
</div>
Post the code of
RepositoryUsuario
– nullptr
Posted @nullptr
– guilhermedjc
Now its entity
Usuario
– nullptr
Pronto @nullptr
– guilhermedjc
one more question, you came to debug and check if the user has the id set when passing the line
repUsuario.save(usuario);
in your service?– nullptr