[英]Grails createCriteria on abstract domain
I am quite curious how one would use the criteria builder to access fields of an inherited class. 我很好奇如何使用条件构建器访问继承的类的字段。
Let's assume we have the following class: 假设我们有以下课程:
class A {
String fieldOne
String fieldTwo
static hasMany = [childs: AbstractChildClass]
}
and the abstract child class would look like this: 并且抽象的子类如下所示:
abstract class AbstractChildClass {
Integer valueOne
Integer valueTwo
A a
static mapping
tablePerHierarchy false
}
}
of course there are several extending classes such as: 当然,有几个扩展类,例如:
class ExtendingClassOne extends AbstractChildClass {
DesiredObject desiredObject
static mapping = {
tablePerHierarchy false
}
}
let's also assume there is the class DesiredObject which looks like this: 我们还假设存在DesiredObject类,如下所示:
class DesiredObject {
String infoA
String infoB
}
The question is how one would get the fields infoA and infoB by creating a criteria for class A. My approach so far is this: 问题是如何通过为类A创建条件来获取字段infoA和infoB。到目前为止,我的方法是:
A.createCriteria().list {
childs {
desiredObject {
ilike('infoA', '%something%')
}
}
}
This of course does not work because in the table ExtendingClassOne is only the id of the desiredObject and I have no clue how to join the object with the criteria builder to get its fields. 这当然是行不通的,因为在表ExtendingClassOne中只是所需对象的ID,我不知道如何将对象与条件构建器结合起来以获取其字段。
Thank you for reading. 感谢您的阅读。
Marco 马尔科
don't expect 100% match between your domain model and the DB schema it's related to. 不要期望您的域模型与其相关的数据库架构之间100%匹配。
In your case the polymorphism would work only with tablePerHierarchy true
for AbstractChildClass. 在您的情况下,多态性仅
tablePerHierarchy true
于AbstractChildClass的tablePerHierarchy true
。
If you do want to stick with tablePerHierarchy false
, you can define your class like: 如果您想坚持使用
tablePerHierarchy false
,则可以像下面这样定义您的类:
class A {
static hasMany = [ childrenOne:ExtendingClassOne, childrenTwo:ExtendingClassTwo ]
}
thus your query would be as simple as: 因此,您的查询将非常简单:
A.withCriteria{
for( String c in [ 'childrenOne', 'childrenTwo' ] ){
"$c"{
desiredObject {
ilike('infoA', '%something%')
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.