我有一些看起来像这样的类:
class User {
boolean enabled
String username
}
class ExampleClass {
User firstUser
User secondUser
}
我的最终目标是找到User
where enabled == true
OR 的实例User
与ExampleClass
.
运行此代码的位置我无权访问变量名称firstUser
或secondUser
.
话虽如此,我需要能够找到关联的所有实例,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" )
}
}