1

I got this error when using Spring 2.7.4: No primary or unique constructor found for class com.library.project.library_el_aleph.model.Client I have two constructors for two possible inserts in my POJO Entity classes

 @Repository
 public interface RoleRespository extends CrudRepository<Role, Integer>{

     Role findByUserName(RoleList roleName);


public Cliente(@NotEmpty @Pattern(regexp = "^[A-Z][a-zA-Z]+") String userName, 
@NotEmpty String email,
    @NotEmpty String contraseña) {
    this.userName = userName;
    this.email = email;
    this.contraseña = contraseña;
}

public Cliente(String productosCliente,
    @NotEmpty @Pattern(regexp = "^[A-Z][a-zA-Z]+") String userName, @NotEmpty String segundoNombre,
    @NotEmpty String primerApellido, @NotEmpty String segundoApellido, @NotEmpty String ciudadCliente,
    @NotEmpty String direccionCliente, @NotEmpty String email, @NotEmpty String contraseña,
    @NotNull @Past Date fechaNacimiento, @NotNull Set<Role> roles) {
    
    this.productosCliente = productosCliente;
    this.userName = userName;
    this.segundoNombre = segundoNombre;
    this.primerApellido = primerApellido;
    this.segundoApellido = segundoApellido;
    this.ciudadCliente = ciudadCliente;
    this.direccionCliente = direccionCliente;
    this.email = email;
    this.contraseña = contraseña;
    this.fechaNacimiento = fechaNacimiento;
    this.roles = roles;
}


}

This is part of the code of my RESTController with the method that sets the @RequesBody inputs:

@RequestMapping(value= "/register", method = RequestMethod.POST)
public ResponseEntity<Object> register(@Valid @RequestBody NewUser newUser, 
BindingResult send){
    
    if(send.hasErrors())
        return new ResponseEntity<>(new Message("Error en el registro, por favor 
    valide nuevamente"), HttpStatus.BAD_REQUEST);

    try {
        Cliente creatingUser = new Cliente(newUser.getPrimerNombre(), 
        newUser.getEmail(), passwordEncoder.encode(newUser.getPassword()));
        Set<Role> roles = new HashSet<>();
        roles.add(roleServices.getRoleByName(RoleList.ROLE_USER).get());
        if(newUser.getRoles().contains("Admin"))
            roles.add(roleServices.getRoleByName(RoleList.ROLE_ADMIN).get());
        creatingUser.setRoles(roles);
        clienteServices.saveNewUser(creatingUser);
        return new ResponseEntity<>(new Message("El usuario ha sido creado correctamente"), HttpStatus.OK);

    } catch (Exception e) {
        return new ResponseEntity<Object>(new Message("Ha ocurrido un error inesperado con el servidor, por favor intente nuevamente más tarde"), HttpStatus.BAD_REQUEST);
        
    }  
} 

It is the first time that I use more than one constructor for the same class and I think that is why the error is due... Can anybody help me?

Toms_Hd3z
  • 129
  • 1
  • 11
  • why do you use those constructors with validation annotations? There's no validation happening as far as I know when you manually "new" objects and annotations can simply go on fields (e.g. https://www.baeldung.com/javax-validation#validation). Entities usually have to have a simple no args constructor for database serialization purposes, you can make it private or protected if you don't want to expose it to regular code – zapl Nov 02 '22 at 01:03
  • When I generate the constructors with my code editor's autocomplete tools it does so. Just omit the constructor annotations, it won't generate any errors on insert or constructor creation. I am new to Java. But I've read that I can't just create a constructor with all the attributes of a class, or an empty constructor and one with all the attributes. I follow this example of constructor overloading but I don't understand what is wrong, I follow the following example of constructor overloading: [link](https://javadesdecero.es/poo/sobrecarga-de-constructores/) – Toms_Hd3z Nov 02 '22 at 02:26
  • 1
    There is nothing wrong with your constructors when it comes to Java itself, the issue is specific to JPA Entities. https://stackoverflow.com/questions/6033905/create-the-perfect-jpa-entity - Once you define a constructor in Java there is no more implicit no-argument constructor. So common practice it to manually add one e.g. simply `protected Cliente() {}`. That constructor is used by the database code to create objects when loaded from the db, the others you define for yourself aren't used – zapl Nov 02 '22 at 11:59
  • @zapl Doing this solved my problem, thank you very much for taking the time to answer and add an explanation – Toms_Hd3z Nov 02 '22 at 15:09

1 Answers1

0

When you override a constructor you must to include the default constructor.

"We must also notice that the java compiler invokes a default constructor when we do not use any constructor in the class. However, the default constructor is not invoked if we have used any constructor in the class, whether it is default or parameterized. In this case, the java compiler throws an exception saying the constructor is undefined."

Solution : Using Lombok @NoArgsConstructor or

public Cliente() {

}

https://www.javatpoint.com/constructor-overloading-in-java