Skip to content
Advertisement

How to get only one role from a set of roles

I’m trying to implement a simple spring security project where basically I have user and role entities. I have a set of roles “ADMIN” and “USER”.

Now I want to assign only “USER” role along with creating a new user.

I have tried to use List and collections with the same problem.

The User entity has Set<Role>

JavaScript

And Role entity:

JavaScript

And here is the saveMyUser method to save the user to my database. When I use:

JavaScript

user.setRoles(new HashSet<>(roleRepository.findAll())); assign all roles to the user, since I want for new user only assign the “USER” role.

I tried user.setRoles(new HashSet<>(roleRepository.findByRole(2))); and also I tried user.setRoles(new HashSet<>(roleRepository.findByID(2))); with this error: Cannot infer type arguments for HashSet<>.

Role table in my database:

JavaScript

Advertisement

Answer

The HashSet constructor takes a Collection, not a single element. This line:

JavaScript

creates a new HashSet with all of your roles. This line

JavaScript

tries to create a new HashSet with a single element in the constructor, which won’t work as a Role is not an instance of Collection.

Just fetch your role, create a HashSet, add the role and THEN set the user’s role:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement