2012-11-06 146 views
0

用戶我有以下幾點:查找特定春季安全角色

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) 

並得到以下錯誤:

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) 

我怎麼只能返回具有特定角色的用戶?

感謝

回答

5

如果你看一看的User#getAuthorities默認實現,你會注意到,該屬性本身就帶有動態取景器調用來實現:

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

因此,你不能指authorities在HSQL查詢,但是您可以通過多種方式在UserRole關聯域類中查詢具有特定角色的用戶:

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

def users = UserRole.findAllByRole(domainRole)?.user 
+0

我嘗試withCriteria版本,我得到的,因爲'從USER_ROLE THIS_選擇this_.user_id爲y0_其中(role_alias1_.authority =?)'的SQLGrammarException。我認爲role_alias1_應該是this_(或者反過來),但是不知道爲什麼它會像這樣產生。任何指針? –

+0

這對於我剛纔在幾分鐘之前遇到的問題確實有幫助,我可以按照邏輯進行操作,但是我不需要查詢關聯使用角色{...} – user615274