Grails table that links to itself

2019-07-20 02:50发布

I would like to create a grails domain class that links to itself.

This related post suggests a solution but I can't get it to work: Grails domain class relationship to itself

For one thing I don’t understand what comparable does and would need to add a int compareTo(obj) method.

Adding the following to my code without implementing Comparable compiles, but grails crashes at runtime:

//NavMenu parent
SortedSet subItems
static hasMany = [subItems: NavMenu]
static belongsTo = [parent: NavMenu]
static constraints = { parent(nullable:true) }

Thanks in advance

2条回答
该账号已被封号
2楼-- · 2019-07-20 03:18

If you don't want to use Comparable interface, maybe you should use List instead of SortedSet.

With a list you can keep objects in the order which they were added and to be able to reference them by index like an array.

This is an example from official docs:

class Author {
    List books

    static hasMany = [books: Book] 
}
查看更多
放荡不羁爱自由
3楼-- · 2019-07-20 03:27

When you're using SortedSet, a sort algorithm is internally executed, but it needs a sort criteria. You need to implement the Comparable interface because that is the standard way to provide a sort criteria to the internal algorithm.

If you don't need a specific order, you can delete the SortedSet subItems line and thus avoid implementing the Comparable interface.

查看更多
登录 后发表回答