gpt4 book ai didi

grails - 有没有办法在Grails中创建与arbitraray域对象的关系

转载 作者:行者123 更新时间:2023-12-02 15:21:55 24 4
gpt4 key购买 nike

有没有办法在grails中创建与任意域对象的关联?

就像是

class ThingHolder {
DomainObject thing;
}

然后
Book b=new Book(title: "Grails 101").save()
Author a=new Author(name: "Abe").save()

ThingHolder t1=new ThingHolder(thing:b).save()
ThingHolder t2=new ThingHolder(thing: a).save()

以便
ThingHolder.get(t1.id).thing  // will be a Book


ThingHolder.get(t2.id).thing  // will be an Author.

最佳答案

我仍在寻找一种更轻松的方式来执行此操作,但这似乎可以完成工作。

class ThingHolder {
static constraints = {
thing bindable:true // required so 'thing' is bindable in default map constructor.
}

def grailsApplication;

Object thing;

String thingType;
String thingId;

void setThing(Object thing) { //TODO: change Object to an interface
this.thing=thing;
this.thingType=thing.getClass().name
this.thingId=thing.id; //TODO: Grailsy way to get the id
}

def afterLoad() {
def clazz=grailsApplication.getDomainClass(thingType).clazz
thing=clazz.get(thingId);
}
}

假设您有一个Book和Author(不覆盖域对象的ID属性)。
def thing1=new Author(name : "author").save(failOnError:true);
def thing2=new Book(title: "Some book").save(failOnError:true);

new ThingHolder(thing:thing1).save(failOnError:true)
new ThingHolder(thing:thing2).save(failOnError:true)

ThingHolder.list()*.thing.each { println it.thing }

在这两个答案中,我发现了一些非常有用的技巧。

How to make binding work in default constructor with transient values.

How to generate a domain object by string representation of class name

关于grails - 有没有办法在Grails中创建与arbitraray域对象的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33926743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com