简体   繁体   中英

Grails Gorm reference a property's (column's) value within a named query?

So... Is there a way to do something like this?

class Kitty {
    String name
    String nickName
    public static String getExpectedNickname(String name) {
        return name.replaceAll('Mr. ', '')
    }
    static namedQueries = {
        byKityWithPredictableNickname {
            ilike 'name', '%Kitty%'
            ilike 'nickName', Kitty.getExpectedNickname('name')
        }
    }
}

Can I reference the value of the current row's column value somehow? I thought property('name') would work, but alas, no.

EDIT:

Another example: I thought something like this would work... but it doesn't :( ...

static namedQueries = {
    whyDoesntThisReturnEverything {
        int c = Kitty.bySubQuery(id).count() //returns everything when I put "1" instead of "id"
        c == 1
    }
    bySubQuery { Long paramId ->
        eq 'id', paramId
    }
}

Instead I get some stupid illegal argument exception:

java.lang.ClassCastException@2af65a43. Stacktrace follows:
Message: java.lang.ClassCastException@2af65a43
    Line | Method
->>   -1 | invoke                                in sun.reflect.GeneratedMethodAccessor327
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|     43 | invoke                                in sun.reflect.DelegatingMethodAccessorImpl
|    606 | invoke . . . . . . . . . . . . . . .  in java.lang.reflect.Method
|   1254 | jlrMethodInvoke                       in org.springsource.loaded.ri.ReflectiveInterceptor
|     90 | invoke . . . . . . . . . . . . . . .  in org.codehaus.groovy.reflection.CachedMethod
|     57 | getProperty                           in groovy.lang.MetaBeanProperty
...

I think the only way to do this is through sqlRestriction .

//...
static namedQueries = {
    findAllKitty {
        ilike 'name', '%Kitty%'
    }

    findAllByNickNameLikeName {
        sqlRestriction "nick_name like '%' || replace(name, 'Mr. ', '') || '%' "
    }
}

//to use:
Kitty.findAllByNickNameLikeName().list()

The SQL syntax will probably change depending on the database you are using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM