title: Spring boot Data Rest: 500 error Validation failed
body: <p>I'm developing a Spring boot web application. and I'm working on spring boot to save users , but i'm getting this error everytime i try to add a caregiver</p>
  <pre><code>Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.validation.ConstraintViolationException: Validation failed for classes [com.bezkoder.springjwt.models.Caregiver] during persist time for groups [javax.validation.groups.Default, ]
  List of constraint violations:[
      ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=password, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
      ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=firstname, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
      ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=username, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
      ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=numcode, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
      ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=email, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
      ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=lastname, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
      ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=gender, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
  ]] with root cause
  </code></pre>
  <p>and this is the error on postman</p>
  <pre><code>&quot;status&quot;: 500,
      &quot;error&quot;: &quot;Internal Server Error&quot;,
      &quot;message&quot;: &quot;Validation failed for classes [com.bezkoder.springjwt.models.Caregiver] during persist time for groups [javax.validation.groups.Default, ]\nList of constraint violations:[\n\tConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=password, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}\n\tConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=firstname, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}\n\tConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=username, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}\n\tConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=numcode, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}\n\tConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=email, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}\n\tConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=lastname, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}\n\tConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=gender, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}\n]&quot;,
      &quot;path&quot;: &quot;/api/auth/signup/c&quot;
  </code></pre>
  <p>this is the code I'm using for the job</p>
  <pre><code>package com.bezkoder.springjwt.models;
  
  import javax.persistence.Entity;
  import javax.persistence.PrimaryKeyJoinColumn;
  import javax.persistence.Table;
  import java.util.Date;
  
  @Entity
  @Table(name = &quot;caregiver&quot;)
  @PrimaryKeyJoinColumn(name = &quot;id&quot;)
  public class Caregiver  extends User {
  
      private static final long serialVersionUID = 1L;
  
      public Caregiver() {
  
      }
  
      public Caregiver(String username, String email, String encode, String firstname, Boolean active, Date dateEntry, Date dateExit, String lastname, String numcode, String gender) {
  
      }
  }
  
  </code></pre>
  <pre><code>package com.bezkoder.springjwt.security.services;
  
  import com.bezkoder.springjwt.models.Caregiver;
  import com.bezkoder.springjwt.models.User;
  import com.fasterxml.jackson.annotation.JsonIgnore;
  import org.springframework.security.core.GrantedAuthority;
  import org.springframework.security.core.authority.SimpleGrantedAuthority;
  import org.springframework.security.core.userdetails.UserDetails;
  
  import java.util.Collection;
  import java.util.Date;
  import java.util.List;
  import java.util.Objects;
  import java.util.stream.Collectors;
  
  public class CaregiverDetailsImpl  implements UserDetails {
     private static final long serialVersionUID = 1L;
  
     private Long id;
  
     private String username;
  
     private String email;
  
     @JsonIgnore
     private String password;
  
  
     private  String firstname;
  
     private Boolean isActive;
  
     private Date dateEntry;
  
     private Date dateExit ;
  
  
     private  String lastname;
  
     private  String numcode;
  
     private  String gender;
  
     private Collection&lt;? extends GrantedAuthority&gt; authorities;
  
     public CaregiverDetailsImpl(Long id, String username, String email, String password,String firstname,
                            Boolean isActive, Date dateEntry, Date dateExit, String lastname,
                            String numcode, String gender,
                            Collection&lt;? extends GrantedAuthority&gt; authorities) {
         this.id = id;
         this.username = username;
         this.email = email;
         this.password = password;
         this.authorities = authorities;
         this.firstname = firstname;
         this.isActive = isActive;
         this.dateEntry = dateEntry;
         this.dateExit = dateExit;
         this.lastname = lastname;
         this.numcode = numcode;
         this.gender = gender;
     }
  
     public static CaregiverDetailsImpl build(Caregiver caregiver) {
         List&lt;GrantedAuthority&gt; authorities = caregiver.getRoles().stream()
                 .map(role -&gt; new SimpleGrantedAuthority(role.getName().name()))
                 .collect(Collectors.toList());
  
         return new CaregiverDetailsImpl(
                 caregiver.getId(),
                 caregiver.getUsername(),
                 caregiver.getEmail(),
                 caregiver.getPassword(),
                 caregiver.getFirstname(),
                 caregiver.getActive(),
                 caregiver.getDateEntry(),
                 caregiver.getDateExit(),
                 caregiver.getLastname(),
                 caregiver.getNumcode(),
                 caregiver.getGender(),
                 authorities);
     }
  
     @Override
     public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {
         return authorities;
     }
  
     public Long getId() {
         return id;
     }
  
     public String getEmail() {
         return email;
     }
  
     public String getFirstname() {
         return firstname;
     }
  
     public Boolean getActive() {
         return isActive;
     }
  
     @Override
     public String getPassword() {
         return password;
     }
  
     @Override
     public String getUsername() {
         return username;
     }
  
     @Override
     public boolean isAccountNonExpired() {
         return true;
     }
  
     @Override
     public boolean isAccountNonLocked() {
         return true;
     }
  
     @Override
     public boolean isCredentialsNonExpired() {
         return true;
     }
  
     @Override
     public boolean isEnabled() {
         return true;
     }
  
     @Override
     public boolean equals(Object o) {
         if (this == o)
             return true;
         if (o == null || getClass() != o.getClass())
             return false;
         CaregiverDetailsImpl caregiver = (CaregiverDetailsImpl) o;
         return Objects.equals(id, caregiver.id);
     }
  }
  </code></pre>
  <pre><code>package com.bezkoder.springjwt.controllers;
  
  import java.util.Date;
  import java.util.HashSet;
  import java.util.List;
  import java.util.Set;
  import java.util.logging.Logger;
  import java.util.stream.Collectors;
  
  import javax.validation.Valid;
  
  import com.bezkoder.springjwt.models.Caregiver;
  import com.bezkoder.springjwt.services.UserService;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.http.HttpStatus;
  import org.springframework.http.ResponseEntity;
  import org.springframework.security.authentication.AuthenticationManager;
  import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  import org.springframework.security.core.Authentication;
  import org.springframework.security.core.context.SecurityContextHolder;
  import org.springframework.security.crypto.password.PasswordEncoder;
  import org.springframework.web.bind.annotation.*;
  
  import com.bezkoder.springjwt.models.ERole;
  import com.bezkoder.springjwt.models.Role;
  import com.bezkoder.springjwt.models.User;
  import com.bezkoder.springjwt.payload.request.LoginRequest;
  import com.bezkoder.springjwt.payload.request.SignupRequest;
  import com.bezkoder.springjwt.payload.response.JwtResponse;
  import com.bezkoder.springjwt.payload.response.MessageResponse;
  import com.bezkoder.springjwt.repository.RoleRepository;
  import com.bezkoder.springjwt.repository.UserRepository;
  import com.bezkoder.springjwt.security.jwt.JwtUtils;
  import com.bezkoder.springjwt.security.services.UserDetailsImpl;
  
  @CrossOrigin(origins = &quot;*&quot;, maxAge = 3600)
  @RestController
  @RequestMapping(&quot;/api/auth&quot;)
  public class AuthController {
  
  
      Logger logger = Logger.getLogger(&quot;com.Appel.lib.Controller.UsersController&quot;);
  
      @Autowired
      private UserService userService ;
  
  
      @Autowired
      AuthenticationManager authenticationManager;
  
      @Autowired
      UserRepository userRepository;
  
      @Autowired
      RoleRepository roleRepository;
  
      @Autowired
      PasswordEncoder encoder;
  
      @Autowired
      JwtUtils jwtUtils;
  
      @PostMapping(&quot;/signin&quot;)
      public ResponseEntity&lt;?&gt; authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
  
          Authentication authentication = authenticationManager.authenticate(
                  new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
  
          SecurityContextHolder.getContext().setAuthentication(authentication);
          String jwt = jwtUtils.generateJwtToken(authentication);
          
          UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();      
          List&lt;String&gt; roles = userDetails.getAuthorities().stream()
                  .map(item -&gt; item.getAuthority())
                  .collect(Collectors.toList());
  
          return ResponseEntity.ok(new JwtResponse(jwt, 
                                                   userDetails.getId(), 
                                                   userDetails.getUsername(), 
                                                   userDetails.getEmail(), 
                                                   roles));
      }
  
      @PostMapping(&quot;/signup&quot;)
      public ResponseEntity&lt;?&gt; registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
          if (userRepository.existsByUsername(signUpRequest.getUsername())) {
              return ResponseEntity
                      .badRequest()
                      .body(new MessageResponse(&quot;Error: Username is already taken!&quot;));
          }
  
          if (userRepository.existsByEmail(signUpRequest.getEmail())) {
              return ResponseEntity
                      .badRequest()
                      .body(new MessageResponse(&quot;Error: Email is already in use!&quot;));
          }
  
          // Create new user's account
          User user = new User(signUpRequest.getUsername(), 
                               signUpRequest.getEmail(),
  
                               encoder.encode(signUpRequest.getPassword()),
  
                                       signUpRequest.getFirstname(),
                  signUpRequest.getActive(),
                  signUpRequest.getDateEntry(),
                  signUpRequest.getDateExit(),
                  signUpRequest.getLastname(),
                  signUpRequest.getNumcode(),
                  signUpRequest.getGender()
  
  
                              );
  
          Set&lt;String&gt; strRoles = signUpRequest.getRole();
          Set&lt;Role&gt; roles = new HashSet&lt;&gt;();
  
          if (strRoles == null) {
              Role userRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                      .orElseThrow(() -&gt; new RuntimeException(&quot;Error: Role is not found.&quot;));
              roles.add(userRole);
          } else {
              strRoles.forEach(role -&gt; {
                  switch (role) {
                  case &quot;admin&quot;:
                      Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                              .orElseThrow(() -&gt; new RuntimeException(&quot;Error: Role is not found.&quot;));
                      roles.add(adminRole);
  
                      break;
                  case &quot;mod&quot;:
                      Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
                              .orElseThrow(() -&gt; new RuntimeException(&quot;Error: Role is not found.&quot;));
                      roles.add(modRole);
  
                      break;
                  default:
                      Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                              .orElseThrow(() -&gt; new RuntimeException(&quot;Error: Role is not found.&quot;));
                      roles.add(userRole);
                  }
              });
          }
  
  
      Boolean isActive = signUpRequest.getActive();
  
  
          if (isActive == null) {
              isActive = true;
  
          }
  
          Date dateEntry = signUpRequest.getDateEntry();
          Date dateExit = signUpRequest.getDateExit();
  
  
          if (dateEntry == null) {
              dateEntry = new Date();
              dateExit =  null;
  
          }
  
  
          user.setRoles(roles);
          user.setActive(isActive);
          user.setDateEntry(dateEntry);
          user.setDateExit(dateExit);
          userRepository.save(user);
  
          return ResponseEntity.ok(new MessageResponse(&quot;User registered successfully!&quot;));
      }
  
  
  
      /***************************** Ad Care giver ****************************/
  
      @PostMapping(&quot;/signup/c&quot;)
      public ResponseEntity&lt;?&gt; registerCaregiver(@Valid @RequestBody SignupRequest signUpRequest) {
          if (userRepository.existsByUsername(signUpRequest.getUsername())) {
              return ResponseEntity
                      .badRequest()
                      .body(new MessageResponse(&quot;Error: Username is already taken!&quot;));
          }
  
          if (userRepository.existsByEmail(signUpRequest.getEmail())) {
              return ResponseEntity
                      .badRequest()
                      .body(new MessageResponse(&quot;Error: Email is already in use!&quot;));
          }
  
          // Create new user's account
          Caregiver caregiver = new Caregiver(signUpRequest.getUsername(),
                  signUpRequest.getEmail(),
  
                  encoder.encode(signUpRequest.getPassword()),
  
                  signUpRequest.getFirstname(),
                  signUpRequest.getActive(),
                  signUpRequest.getDateEntry(),
                  signUpRequest.getDateExit(),
                  signUpRequest.getLastname(),
                  signUpRequest.getNumcode(),
                  signUpRequest.getGender()
  
  
          );
  
          Set&lt;String&gt; strRoles = signUpRequest.getRole();
          Set&lt;Role&gt; roles = new HashSet&lt;&gt;();
  
          if (strRoles == null) {
              Role userRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                      .orElseThrow(() -&gt; new RuntimeException(&quot;Error: Role is not found.&quot;));
              roles.add(userRole);
          } else {
              strRoles.forEach(role -&gt; {
                  switch (role) {
                      case &quot;admin&quot;:
                          Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                                  .orElseThrow(() -&gt; new RuntimeException(&quot;Error: Role is not found.&quot;));
                          roles.add(adminRole);
  
                          break;
                      case &quot;mod&quot;:
                          Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
                                  .orElseThrow(() -&gt; new RuntimeException(&quot;Error: Role is not found.&quot;));
                          roles.add(modRole);
  
                          break;
                      default:
                          Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                                  .orElseThrow(() -&gt; new RuntimeException(&quot;Error: Role is not found.&quot;));
                          roles.add(userRole);
                  }
              });
          }
  
          Boolean isActive = signUpRequest.getActive();
  
  
          if (isActive == null) {
              isActive = true;
  
          }
  
          Date dateEntry = signUpRequest.getDateEntry();
          Date dateExit = signUpRequest.getDateExit();
  
  
          if (dateEntry == null) {
              dateEntry = new Date();
              dateExit =  null;
  
          }
  
  
          caregiver.setRoles(roles);
          caregiver.setActive(isActive);
          caregiver.setDateEntry(dateEntry);
          caregiver.setDateExit(dateExit);
          userRepository.save(caregiver);
  
          return ResponseEntity.ok(new MessageResponse(&quot;User registered successfully!&quot;));
      }
  
      @GetMapping(path = &quot;/getuser&quot;)
      public ResponseEntity&lt;List&lt;User&gt;&gt; getAllUsers() {
  
          logger.info(&quot;Getting all Users  from Users table...Call getAllUsers() &quot;);
          return ResponseEntity.ok(userService.getAll());
      }
  
      @GetMapping(path = &quot;getById/{id}&quot;)
      public ResponseEntity&lt;User&gt; getUserById(@PathVariable Long id) {
          logger.info(&quot;Getting all Users  by id from User table...Call getUserById() &quot;);
          User  user = userService.get(id);
          return user != null ? ResponseEntity.ok(user) : new ResponseEntity&lt;User&gt;(HttpStatus.NOT_FOUND);
      }
  
      @PutMapping(path = &quot;Update/{id}&quot;)
      public ResponseEntity&lt;User&gt; updateUser(@PathVariable Long id, @RequestBody User user) {
  
          logger.info(&quot;Add new  Users  to  Users table...Call updateUser() &quot;);
  
          if (id != null &amp;&amp; user.getId() != null &amp;&amp; user.getId() == id) {
              user.setActive(true);
              User  modifyuser = userService.save(user);
              return modifyuser != null &amp;&amp; modifyuser.getId() != null ? ResponseEntity.ok(modifyuser)
                      : new ResponseEntity&lt;User&gt;(HttpStatus.NOT_MODIFIED);
          }
          else {
              return new ResponseEntity&lt;User&gt;(HttpStatus.NOT_MODIFIED);
          }
      }
  
      @DeleteMapping(path = &quot;Delete/{id}&quot;)
      public ResponseEntity&lt;String&gt; deleteUser(@PathVariable Long id, @RequestBody User user) {
  
          logger.info(&quot;Desactive  Users  from  Users table...Call deleteUser() &quot;);
  
      //  Date dateExit = new Date();
  
  
          if (id != null &amp;&amp; userService.get(id) != null) {
  
              user.setActive(false);
  
              user.setDateExit(new Date());
  
              userService.save(user);
              //userService.delete(id);
              return ResponseEntity.ok(&quot;Deleted&quot;);
          }
  
          return new ResponseEntity&lt;String&gt;(HttpStatus.NOT_FOUND);
  
      }
  }
  </code></pre>
  <pre><code>package com.bezkoder.springjwt.models;
  
  import java.io.Serializable;
  import java.util.Date;
  import java.util.HashSet;
  import java.util.Set;
  
  import javax.persistence.*;
  import javax.validation.constraints.Email;
  import javax.validation.constraints.NotBlank;
  import javax.validation.constraints.Size;
  
  @Entity
  
  @Table( name = &quot;users&quot;, 
          uniqueConstraints = { 
              @UniqueConstraint(columnNames = &quot;username&quot;),
              @UniqueConstraint(columnNames = &quot;email&quot;) 
          })
  
  @Inheritance(strategy = InheritanceType.JOINED)
  
  public class User   implements  Serializable{
  
      private static final long serialVersionUID = 1L;
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;
  
      @NotBlank
      @Size(max = 20)
      private String username;
  
      @NotBlank
      @Size(max = 50)
      @Email
      private String email;
  
      @NotBlank
      @Size(max = 120)
      private String password;
  
      @ManyToMany(fetch = FetchType.LAZY)
      @JoinTable( name = &quot;user_roles&quot;, 
                  joinColumns = @JoinColumn(name = &quot;user_id&quot;), 
                  inverseJoinColumns = @JoinColumn(name = &quot;role_id&quot;))
      private Set&lt;Role&gt; roles = new HashSet&lt;&gt;();
  
  
      @NotBlank
      private String firstname;
  
  
     private Boolean isActive  ;
  
      @Column( nullable = false, unique = true, updatable = false)
     private Date dateEntry ;
  
      @Column(  unique = true)
      private Date dateExit ;
  
      @NotBlank
      private  String lastname;
  
      @NotBlank
      private  String numcode;
  
      @NotBlank
      private  String gender;
  
  
  
  
  
  
      public User(String username, String email, String password, String firstname, Boolean active,
                  Date dateEntry, Date dateExit , String lastname, String numcode, String gender) {
          this.username = username;
          this.email = email;
          this.password = password;
          this.roles = roles;
          this.firstname = firstname;
          this.isActive = active;
          this.dateEntry = dateEntry;
          this.dateExit = dateExit;
          this.lastname = lastname;
          this.numcode = numcode;
          this.gender = gender;
  
      }
  
  
      public User() {
  
      }
  
  
      public Long getId() {
          return id;
      }
  
      public void setId(Long id) {
          this.id = id;
      }
  
      public String getUsername() {
          return username;
      }
  
      public void setUsername(String username) {
          this.username = username;
      }
  
      public String getEmail() {
          return email;
      }
  
      public void setEmail(String email) {
          this.email = email;
      }
  
      public String getPassword() {
          return password;
      }
  
      public void setPassword(String password) {
          this.password = password;
      }
  
      public Set&lt;Role&gt; getRoles() {
          return roles;
      }
  
      public void setRoles(Set&lt;Role&gt; roles) {
          this.roles = roles;
      }
  
  
      /* ################ Ad attribut ################### */
  
      public String getFirstname() {
          return firstname;
      }
  
      public void setFirstname(String firstname) {
          this.firstname = firstname;
      }
  
      public Boolean getActive() {
          return isActive;
      }
  
      public void setActive(Boolean active) {
          isActive = active;
      }
  
      public Date getDateEntry() {
          return dateEntry;
      }
  
      public void setDateEntry(Date dateEntry) {
          this.dateEntry = dateEntry;
      }
  
      public Date getDateExit() {
          return dateExit;
      }
  
      public void setDateExit(Date dateExit) {
          this.dateExit = dateExit;
      }
  
      public String getLastname() {
          return lastname;
      }
  
      public void setLastname(String lastname) {
          this.lastname = lastname;
      }
  
      public String getNumcode() {
          return numcode;
      }
  
      public void setNumcode(String numcode) {
          this.numcode = numcode;
      }
  
      public String getGender() {
          return gender;
      }
  
      public void setGender(String gender) {
          this.gender = gender;
      }
  }
  
  </code></pre>
  <p>postman request</p>
  <pre><code>{
  &quot;username&quot;:&quot;konf&quot;,
  &quot;email&quot;:&quot;hdnr@kox.yn&quot;,
  &quot;password&quot;:&quot;fvnnnd&quot;,
  &quot;firstname&quot;:&quot;hhhh&quot;,
  &quot;lastname&quot;:&quot;hdjdh&quot;,
  &quot;numcode&quot;:&quot;dhdhdh&quot;,
  &quot;gender&quot;:&quot;hhfhf&quot;
  
  }
  </code></pre>
  <p>i searched stackoverflow for any solution , but i didn't find any, by the way i'm using the same code to add a user and its working fine , but when using the same code to add a caregiver i get the error</p>