开发者

Polymorphic belongsTo in many to many mapping in grails?

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.

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)
  }
}

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 Taggable table for Tag.References to reference with a foreign key.

  1. Discriminator will NOT defeat polymorphism, if it's added automatically - for instance, in table-per-hierarchy mapping, Hibernate/Gorm adds a class field in order to find out a concrete class when reading object from db.

  2. If you map your Taggables 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.

BTW class field is pretty long - it contains fully qualified class name.

edit 2: Either way, it's getting pretty complex, and I'd personally go with the approach I suggested in another question:

  • dynamically query all the classes with Taggable interface for hasMany=[tags:Tag] property;
  • or, less preferable - to have a hand-crafted child table and a discriminator.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜