Grails GORM:我如何创建一个复合主键并将其用于表关系? [英] Grails GORM: How do I create a composite primary key and use it for a table relationship?
问题描述
我有两个表,其中一个表(旧表:A)有两个字段应该用作复合外键,另一个表(新表:B)应该为<$ c $使用复合主键c>每一行:A有一行:B 关系。我如何用GORM来描述这些表?
到目前为止,我已经能够创建一个反映遗留表的域类:A
class A {
...
//复合外键链接B class
String className;
字符串eventName;
B b; // B的实例关联
static mapping = {
table'a_table';
id列:'id';
className列:'class_name';
eventName列:'event_name';
// b:???
$ / code $ / pre
可以工作,但我无法创建 new class:B
和关系。
我试图将B声明为:
class B实现了Serializable {
static auditable = true;
字符串名称;
String className;
字符串eventName;
static mapping = {
//假设要创建一个复合PK
id复合:[className,eventName]
}
}
但这不会使用
ERROR context.GrailsContextLoader进行编译 - 执行引导时出错:为域[com.package.B]计算ORM映射块时出错:没有这样的属性:类名为eventName:org.codehaus.groovy.grails.orm.hibernate.cfg.HibernateMappingBuilder
我想要的是这样的:
static mapping = {
...
b复合:[b.className:className,b.eventName:eventName]
//或者其他任何方法都可以完成。
}
为A类使GORM处理这种关系。
解决方案您是否尝试使用属性名称而不是使用属性值?
类B实现Serializable {
字符串名称;
String className;
字符串eventName;
静态映射= {
//应该创建一个复合PK
id复合:['className','eventName']
}
}
和A中的映射:
class A {
static hasMany = [b:B]
}
在 A 中不需要有 className
或 eventName
code>
I have two tables, one of which (legacy table: A) has two fields that should serve as a composite foreign key and the other one (new table: B) should use a composite primary key for a each row:A has one row:B
relationship. How do I describe these tables in terms of GORM?
So far I've been able to create a domain class that reflects the legacy table:A
class A {
...
//composite foreign key to link B class
String className;
String eventName;
B b; //instance of B to be related
static mapping = {
table 'a_table';
id column: 'id';
className column: 'class_name';
eventName column: 'event_name';
//b: ???
}
}
which works, but I can't create a new class:B
and the relationship.
I tried to declare B as:
class B implements Serializable{
static auditable = true;
String name;
String className;
String eventName;
static mapping = {
//supposed to make a composite PK
id composite:[className, eventName]
}
}
but this won't compile with a
ERROR context.GrailsContextLoader - Error executing bootstraps: Error evaluating ORM mappings block for domain [com.package.B]: No such property: eventName for class: org.codehaus.groovy.grails.orm.hibernate.cfg.HibernateMappingBuilder
What I want is something like:
static mapping = {
...
b composite: [b.className:className, b.eventName:eventName]
//or whatever is the right way for this to be done.
}
for the A class to make GORM handle this relation.
解决方案 Did you try to use attribute name instead of use attribute value ?
class B implements Serializable{
String name;
String className;
String eventName;
static mapping = {
//supposed to make a composite PK
id composite:['className', 'eventName']
}
}
And mapping in A :
class A {
static hasMany = [ b : B ]
}
No need to have className
or eventName
in A
这篇关于Grails GORM:我如何创建一个复合主键并将其用于表关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!