按sting List中的id排序对象列表

时间:2017-05-24 11:23:58

标签: sorting grails

我有一个带有Java 7的grails应用程序。在这里我有一个List表和表中的Items表,如下所示。它是多对多的关系,其中List是父级,而对于规范化,我有List_Item类,因此正常的功能正在按预期工作。

Class Parent{
    static hasOne{list:List}    
}

Class List{
    ....
    static hasMany{item:Item}
    static hasOne{listOrder:ListOrder}
}

Class Item{
    Long id
    .....
}

现在我必须在列表中存储项目的顺序。所以我创建了以下结构

Class ListOrder{
    Long id
    List list
    //Stores all the ids as a coma separated string in the necessary order
    String order
}

因此,每次更改订单时,都要更新ListOrder记录。

现在我需要一种方法来在检索List或Parent类时使用存储的ID Sting对项进行排序。我希望通过名称为' orderItems()'的List域对象中的方法实现此目的,其中当我调用此方法时,List对象中的item参数将被设置为已排序的List对象。

我想到的想法类似于以下代码

Class List{
    ....
    orderItems(){
        this.item = this.item.sort(this.itemOrder.order.split(','))
    }
    ....
}

我如何实现这一目标,还是有更好的方法来实现这一目标?根据要求,List可以包含100多个项目,因此我选择不单独存储每个项目位置。

2 个答案:

答案 0 :(得分:0)

不完全确定你在做什么。但只是排序列表? 如果列表中的项目是对象,则可以对任何这些对象字段进行排序。

   Class obj {
     String name
     String status
     String desc
   }

   List objList = .... List of obj
   obj.sort {a, b -> a.name <=> b.name} // Sort by name
   obj.sort {a, b -> a.status <=> b.status} // Sort by status
   obj.sort {a, b -> a.desc <=> b.desc} // Sort by desc

列表可以存储数百万个项目,因此请不要创建字符串。

答案 1 :(得分:0)

我已经阅读了几次,并且认为我了解最终用户正在尝试实现的目标,并认为这是他们想要尝试管理有限的hasMany关系的一些自定义方式。

这个过程存在缺陷,我将解释原因。

通过一个名为id的String字段包含一个id列表。您只能真正能够在没有复杂查询的情况下对列表进行排序。一旦拆分等等,这是一种业余的关系思维方式。

这就是你必须先查找第一个对象的原因。然后,一旦迭代完成自己的进程,就可以加载应该映射的id的实际记录。这意味着编写一个查询以便在此实例中无缝地工作以查找挂起的特定给定关系将非常困难。

而不是完成所有这些

Class Example1 {
   //Would have 
  // static hasMany = [ example2:Example2]
  //but in your case
   String examples2=1,2,10000001122,33222222332222,023222434343243, 
   //and so on
}

所以你有两个选择..

Class Example1 {
   //Would have 
   static hasMany = [ example2:Example2]
   static constrains= {
     example2:validator: checkExample
    }
  static def checkExample={val,obj,errors->
        if (val && val.size()>100) {
            errors.rejectValue('', "toomany.records", [''] as Object[], '')
        }
    }
}
上面的

将限制为100个hasMany,如果为反向设置了belongsTo,则可以从主对象或反向对象进行无缝查询访问。

如果您这样想的话,这一切都很简单:

class Example1 {
  //nothing at all about example2 as yet


    Set<Example2> getExample2BySortedGivenField() {
       //either a set or a list that then you write your HQL 
       // or some specific query to return object by given sorting
        return Example2.findAllByExample(this)

    }

   //you can have a few different onces if needed or a dynamic method that passes in what to sort by - the output will be what you have asked for in question

}

现在在类Example2中,您只需在主类

中绑定
class Example2 {
  //Simply bind the primary object in example2 class no need to do 
  // additional work in example2 to manage beyond query
  Example1 example1
}
相关问题