Question

I have the following:

def userInstance=User.findAll("from User u where u.merchant is not null and u.merchant.id = ? and u.authorities.authority.contains('ROLE_MERCHANT')", merchantId)

And get the following error:

org.hibernate.hql.ast.QuerySyntaxException: unexpected AST node: ( near line 1, column 121 [from com.testing.tests.User u where u.merchant is not null and u.merchant.id = ? and u.authorities.authority.contains('ROLE_MERCHANT')]
    at $Proxy20.createQuery(Unknown Source)
    at testing.admin.UserService.findByMerchantId(UserService.groovy:14)

How can I return only users that have a specific role?

Thanks

Was it helpful?

Solution

If you take a look at the default implementation of User#getAuthorities you will note that the property is itself implemented with a dynamic finder call:

UserRole.findAllByUser(this).collect { it.role } as Set

Therefore you can not refer to authorities in the HSQL query, but you can query users with a specific role over the UserRole association domain class in multiple ways:

def users = UserRole.withCriteria {
   role{
       eq 'authority', 'ROLE_SOMETHING'
   }
   projections{
      property 'user'
   }
}

or

def users = UserRole.findAllByRole(domainRole)?.user
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top