Search code examples
sortinggrailscompareto

Overriding compareTo on self-referencing object (parent/child relationship)


I'm trying to implement compareTo on a domain class in grails so I can return a SortedSet. I want my sorted set to be ordered by parent name, then by "child" name. For example (P=parent, C=child):

  • P-1
    • C-1
    • C-2
  • P-2
    • C-3
    • C-4

My class looks something like this:

class Issue implements Comparable {
 String name
 Issue parent

@Override
public int compareTo(obj){
  if(obj.parent!=null && this.parent!=null){
   parent.name.compareTo(obj.parent.name)
  }else{
      //What do I compare to sort the children relative to their parents?
  }
}

Solution

  • If all you're looking for is sorted sets, would just implementing Comparable on Issue and using sort orders on the mappings suffice?

    class Issue implements Comparable {
     String name
     Issue parent
     SortedSet children
    
     static hasMany = [children : Issue]
     static belongsTo = [parent : Issue]
     static mapping = {
        sort 'name'
        children sort:'name'
     }    
    
    @Override
    public int compareTo(obj){
      if(obj){
        this.name?.compareTo(obj.name)
      }
    }