0

I have a problem with sending a registration request to the Postman.

I have an issue with the roles array.

Even if I define all values which contains username, email, password, and lastly role value, I get an error message in Postman. (detached entity passed to persist).

How can I fix it?

Here is my IdBasedEntity class shown below.

@MappedSuperclass
@Getter
@Setter
public class IdBasedEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Integer id;
}

Here is my signup dto shown below.

@Data
@AllArgsConstructor
@NoArgsConstructor
public class SignupRequest {

    @NotBlank
    @Size(min = 3, max = 20)
    private String username;

    @NotBlank
    @Size(min = 6, max = 40)
    private String password;

    @NotBlank
    @Size(max = 50)
    @Email
    private String email;

    private Set<String> roles;

}

Here is my Postman request is shown below.

{
    "username" : "User1",
    "password" : "user1",
    "email" : "user_role_user@refreshtoken.com",
    "roles" : [
        "ROLE_USER"
    ]
}

Here is my register method shown below.

@PostMapping("/signup")
    public ResponseEntity<?> registerUser(@RequestBody SignupRequest signUpRequest) {

        LOGGER.info("AuthController | registerUser is started");

        String username = signUpRequest.getUsername();
        String email = signUpRequest.getEmail();
        String password = signUpRequest.getPassword();
        Set<String> strRoles = signUpRequest.getRoles();
        Set<Role> roles = new HashSet<>();

        if(userService.existsByUsername(username)){
            return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
        }

        if(userService.existsByEmail(email)){
            return ResponseEntity.badRequest().body(new MessageResponse("Error: Email is already taken!"));
        }

        User user = new User();
        user.setEmail(email);
        user.setUsername(username);
        user.setPassword(encoder.encode(password));


        if (strRoles != null) {
            strRoles.forEach(role -> {
                switch (role) { -> ERROR HERE
                    case "ROLE_ADMIN":

                        Role adminRole = roleService.findByName(ERole.ROLE_ADMIN)
                                .orElseThrow(() -> new RoleException("Error: Admin Role is not found."));
                        roles.add(adminRole);
                        break;

                    case "ROLE_MODERATOR":

                        Role moderatorRole = roleService.findByName(ERole.ROLE_MODERATOR)
                                .orElseThrow(() -> new RoleException("Error: Moderator Role is not found."));
                        roles.add(moderatorRole);

                        break;

                    default:

                        Role userRole = roleService.findByName(ERole.ROLE_USER)
                                .orElseThrow(() -> new RoleException("Error: User Role is not found."));
                        roles.add(userRole);

                }

            });
        }else{

            Role userRole = new Role();
            userRole.setName(ERole.ROLE_USER);

            roles.add(userRole);
        }

        user.setRoles(roles);
        userService.saveUser(user);

        return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
    }

Here is my error shown below.

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.refreshtokenjwt.app.modal.Role; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.refreshtokenjwt.app.modal.Role] with root cause
S.N
  • 2,157
  • 3
  • 29
  • 78
  • Can you post the error here? I think that default case is being used. The Not Found is probably from roleService.findByName(ERole.ROLE_USER). Anyway you can debug and check what you are receiving in strRoles. Clearly is not null nor empty. – pringi Mar 08 '22 at 10:03
  • @pringi I just posted error here – S.N Mar 10 '22 at 16:02
  • With the given error, the problem is more likely to be here: userService.saveUser(user);. It dependes how role is configured as entity. Maybe this helps: https://stackoverflow.com/questions/10168579/detached-entity-passed-to-persist – pringi Mar 10 '22 at 16:07
  • @pringi I used IdBasedEntity for defining id. – S.N Mar 10 '22 at 16:11
  • The exception you are getting is different from the original question. I suggest you to open a new question. – pringi Mar 10 '22 at 16:13
  • @pringi I think there is a problem here . private Set roles = new HashSet<>(); – S.N Mar 10 '22 at 16:28

0 Answers0