开发者

Query the other way across a one-to-many with Criteria Builder

Lets say I have the following one-to-many relationship:

Site has many Users
User belongs to one Site

I've setup the relationship like this

class Site {
    static hasMany = [users:User]
    ...
}

and

class User {
    static belongsTo = [site:Site]
    int number
    String username
    ...
}

Basically I want to update the username for a par开发者_StackOverflowticular User on a particular Site and return the User object. I know the Site and the new Username so I have a function that tries to lookup the corresponding connection by using a criteria builder:

class funcClass {
    User func(Site site, int number, String newUserName) {
        def results = User.createCriteria()
        results.list = {
             eq('number', number)
             site {
                 idEq(site.id)
             }
        }
        ...
        def user = results[0]
        ...
        return user
    }
}

I get an exception similar to:

groovy.lang.MissingMethodException: No signature of method: static com.myapp.Site.call() is application for arguemtns types: ( funcClass$_closure )

Is this possible with Criteria Builder? I realize I can do the query the otherway, where I build the Criteria down from Site to User, but then I have to loop through all of the Users for the Site to find the one that matches the number I was looking to update. Am I just going to have to use an HQL query?


It should be

def criteria = User.createCriteria()
def users = criteria.list {
   eq('site', site)
   eq('number', number)
   maxResults(1)
}
def user = users[0]

but you can do this with a simple dynamic finder:

def user = User.findBySiteAndNumber(site, number)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜