问题描述
所以我知道这是可能的使用超类,但是,这是非常限制的灵活性。所以我的问题是,我可以使用接口吗? 界面Taggable {
/ *添加标签并返回当前设置的标签列表* /
列表< String> addTags(String ...标签)
/ *删除标签并返回当前设置的标签列表* /
List< String> removeTags(String ... tag)
}
class用户实现Taggable {
字符串用户名
static hasMany = [tags:Tag]
}
类标记{
字符串名称
静态hasMany = [引用:Taggable]
static belongsTo = Taggable
静态约束= {
name(可空:假,空白:假,唯一:真)
}
}
我对带有以下标记的对象的引用感兴趣。但是这个对象不能扩展一个具体的类。这就是为什么即时通讯想知道这是否可以用接口来完成。
所以,可以这样做吗?
$ b $ Hibernate可以映射一个接口 - 。我怀疑Grails是否支持按惯例映射 - 但您可以尝试使用映射 from above example,or XML config。 edit :回答评论问题: 在数据库级别,必须为 Discriminator will not如果它是自动添加的 - 例如,在每个层次的表映射中,Hibernate / Gorm会添加一个 编辑2 : So i know this is possible using a superclass, however, this is very limiting in flexibility. So my question is then, can i use an interface? Something ala. Im interested in a reference back to the object who has the following tag. This object however can't extend a concrete class. Thats why im wondering if this can be done with an interface instead. So, can it be done? Hibernate can map an interface - see example. I doubt if Grails supports this in by-convention mapping - but you can try using the mapping annotations from example above, or XML config. edit: answering a comment question: On a database level, you have to have a Discriminator will NOT defeat polymorphism, if it's added automatically - for instance, in table-per-hierarchy mapping, Hibernate/Gorm adds a If you map your BTW edit 2:Either way, it's getting pretty complex, and I'd personally go with the approach I suggested in another question: 这篇关于多态属于Grails中的多对多映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
Taggable
表 Tag.References
引用一个外键。
class
字段,以便在读取对象时找到具体的类如果你将 Taggable
s映射到两个表 - Taggable
部分为 Taggable
以及其他所有内容添加到特定表格,参考1:1 - 所有鉴别器都可以工作应该由Hibernate为您完成。
无论哪种方式,它变得非常复杂,我个人会采用我在另一个问题中建议的方法:
hasMany = [tags:Tag]
属性; li>
interface Taggable {
/*Adds tag(s) and returns a list of currently set tags*/
List<String> addTags(String ... tag)
/*Removes tag(s) and returns a list of currently set tags*/
List<String> removeTags(String ... tag)
}
class User implements Taggable {
String username
static hasMany = [tags:Tag]
}
class Tag {
String name
static hasMany = [references:Taggable]
static belongsTo = Taggable
static constraints = {
name(nullable: false, blank: false, unique: true)
}
}
Taggable
table for Tag.References
to reference with a foreign key.class
field in order to find out a concrete class when reading object from db.Taggable
s to two tables - Taggable
part to Taggable
and everything else to specific table, referenced 1:1 - all the discriminator work should be done for you by Hibernate.class
field is pretty long - it contains fully qualified class name.hasMany=[tags:Tag]
property;