Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9214847
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T02:03:51+00:00 2026-06-18T02:03:51+00:00

I want to retrieve all users which have a specific Role like ROLE_USER. Below

  • 0

I want to retrieve all users which have a specific Role like “ROLE_USER”.

Below are Domain Classes for User, Role and UserRole.

User.groovy

class User {

    transient springSecurityService

    String username
    String password
        String email
    boolean enabled
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired

    static constraints = {
        username blank: false, unique: true
        password blank: false
    }

    static mapping = {
        password column: '`password`'
    }

    Set<Role> getAuthorities() {
        UserRole.findAllByUser(this).collect { it.role } as Set
    }

    def beforeInsert() {
        encodePassword()
    }

    def beforeUpdate() {
        if (isDirty('password')) {
            encodePassword()
        }
    }

    protected void encodePassword() {
        password = springSecurityService.encodePassword(password)
    }
}

Role.groovy

class Role {

    String authority

    static mapping = {
        cache true
    }

    static constraints = {
        authority blank: false, unique: true
    }
}

UserRole.groovy

class UserRole implements Serializable {

    User user
    Role role

    boolean equals(other) {
        if (!(other instanceof UserRole)) {
            return false
        }

        other.user?.id == user?.id &&
            other.role?.id == role?.id
    }

    int hashCode() {
        def builder = new HashCodeBuilder()
        if (user) builder.append(user.id)
        if (role) builder.append(role.id)
        builder.toHashCode()
    }

    static UserRole get(long userId, long roleId) {
        find 'from UserRole where user.id=:userId and role.id=:roleId',
            [userId: userId, roleId: roleId]
    }

    static UserRole create(User user, Role role, boolean flush = false) {
        new UserRole(user: user, role: role).save(flush: flush, insert: true)
    }

    static boolean remove(User user, Role role, boolean flush = false) {
        UserRole instance = UserRole.findByUserAndRole(user, role)
        if (!instance) {
            return false
        }

        instance.delete(flush: flush)
        true
    }

    static void removeAll(User user) {
        executeUpdate 'DELETE FROM UserRole WHERE user=:user', [user: user]
    }

    static void removeAll(Role role) {
        executeUpdate 'DELETE FROM UserRole WHERE role=:role', [role: role]
    }

    static mapping = {
        id composite: ['role', 'user']
        version false
    }
}

These Domain Classes are generated by Spring Security plugin.
I have added only email field for User class.

Here is my UserController.groovy

class UserController {

    def index = {
       }


    def list = {

        def role = Role.findByAuthority("ROLE_USER")
        println "role id "+role.id

        def users = User.findAll()         //Its giving me all Users regardless of Role
        println "total users "+users.size()
        for(user in users)
        {
            println "User "+user.username+" "+user.email
        }
        render (view: "listUsers", model:[users:users])

    }
}

In the list action I used User.findAll() but its giving me all user with all roles.
I want user list only from a certain role..

EDIT

Code to Assign Roles to newly created user

def username = params.username
def emailID = params.emailID
def password = params.password

def testUser = new User(username: username, enabled: true, password: password,email:emailID)
testUser.save(flush: true)
def userRole = new Role(authority: 'ROLE_USER').save(flush: true)
UserRole.create testUser, userRole, true

Thanks..

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T02:03:52+00:00Added an answer on June 18, 2026 at 2:03 am

    Replace

    def users = User.findAll()
    

    with

    def users = UserRole.findAllByRole(role).user
    

    and you should get all users with the required role.

    EDIT

    In your code sample you try to create a new Role for the User. Since a Role with the authority ROLE_USER already exists and authority has to be unique (see the ‘constraints’ part in your Role class) this new Role cannot be saved to the database. Because the Role you assign in UserRole.create doesn’t exist in the database the UserRole is not saved either. You would have to assign the existing Role to the new User (e.g. with `Role.findByAuthority’).

    Creating the roles in Bootstrap.groovy is a good idea according to Spring Source because roles “are typically defined early in the life of the application and correspond to unchanging reference data. That makes BootStrap the ideal place to create them.” (Spring Source Blog)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to retrieve a set of results, which consist of all results produced
I want to retrieve declared SVG attributes programmatically. It's all inline content, something like
I want to select from the following table all the rows which have similar
Let's say I have a REST API, which has basic methods to retrieve users
I want to retrieve all ids within a certain timespan. The timestamps however, are
I want to retrieve all clientID from my MCC account. I'm using this code
I want to retrieve all records from one table when there are no matches
I want to retrieve all objects (not DOM elements) of a given type created
I want to retrieve all documents from folder to it's subfolder and so on
I retrieve a list of ObjectId and I want to retrieve all object in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.