我正在遗留数据库上创建一个 grails 应用程序。
有一个表,我想从中创建几个不同的域对象(下面示例中的 Type1、Type2 和 Type3)。
表格是这样的:
ID TYPE DESCRIPTION
1 type1 description of a type1 object
2 type1 description of another type1 object
3 type2 description of a type2 object
4 type3 description of a type3 object
...
所以我想创建 3 个不同的域类,每个域类包含一个名为“描述”的字段,并对应于一个特定的“类型”,因为行代表不同的概念。
是否有任何类型的约束允许我按类型过滤行?
我的意思是,我可以做类似的事情吗:
class Type1 {
String type
String description
static mapping = {
table 'mytable'
}
static constraints = { type == 'type1' } // Is there anything like this ?
}
然后我希望 Type1.list() 产生如下查询:
SELECT type, description
FROM mytable
WHERE type = 'type1'
更新:
实际上是 documentation说我可以使用鉴别器来实现这一点。
但是,我尝试按如下方式设置我的类(class):
class Type1 extends BaseType {
static mapping = {
discriminator column:'type', value: 'type1'
}
}
我激活了休眠 SQL 跟踪,而不是看到
SELECT ... FROM mytable WHERE type = 'type1'
我明白了
SELECT ... FROM mytable WHERE class = 'type1'
鉴别器似乎完全忽略了我的自定义列名:-(
我正在使用 Grails 1.2.1
最佳答案
好的,Grails 文档不是最新的 (it should though)。
解决方案是:
在 BaseType 类中:
static mapping = { discriminator column:"type" }
在子类中:
static mapping = { discriminator value:"type1" } // or type2, type3, etc...
关于orm - 使用 GORM DSL 将多个域对象映射到同一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2379371/