0

我有一些看起来像这样的类:

class User {
    boolean enabled
    String username
}

class ExampleClass {
    User firstUser
    User secondUser
}

我的最终目标是找到Userwhere enabled == trueOR 的实例UserExampleClass.

运行此代码的位置我无权访问变量名称firstUsersecondUser.

话虽如此,我需要能够找到关联的所有实例,User而不管关联是通过ExampleClass哪个变量(firstUser或)。secondUser 我该怎么做呢?

更新:

我能想到的最好的方法是我的User域类中的这种方法。在上面给出的示例中,我有一个类型ExampleClass的多个字段User。事实上,我有多个具有多个类型字段的User类。这就是为什么我从传入的对象中获取域类,而不仅仅是键入ExampleClass.

static List findAllEnabledOrAssociatedWith( Object obj = null ) {
    if( obj?.id ) { // Make sure the object in question has been saved to database.
        List list = [] 
        obj.domainClass.getPersistentProperties().each {
            if( it.getReferencedPropertyType() == User ) {
                def propertyName = it.getName()
                list += User.executeQuery( "SELECT DISTINCT ${propertyName} FROM ${obj.class.getSimpleName()} obj INNER JOIN obj.${propertyName} ${propertyName} WHERE obj =:obj", [ obj: obj ] )
            }
        }
        list.unique()
        return User.executeQuery( "SELECT DISTINCT users FROM User users WHERE users.enabled=true OR users IN(:list)", [ list: list ] )
    } else {
        return User.executeQuery( "SELECT DISTINCT users FROM User users WHERE users.enabled=true" )
    }
}
4

1 回答 1

0
def sql = '''
    from 
        User u, 
        ExampleClass ex 
    where 
        u.enabled = 1 or (u = ex.firstUser or u = ex.secondUser)'''
def users = User.findAll(sql)
于 2012-08-31T20:11:06.553 回答