Grails table that links to itself

末鹿安然 提交于 2019-12-11 03:19:58

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/12201420/grails-table-that-links-to-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!