开发者

Retrieiving domain object instances as a Map

I wonder if there is a way to retreive domain instances as a Map where the key is the开发者_如何学运维 id of the domain object.

more specific i would like to do myDomainObject.list() to return a Map instead of a List.


You can create this method easily in your domain class, for example:

class Person {

   String name

   static Map<Long, Person> mapAll() {
      def map = [:]
      list().each { map[it.id] = it }
      map      
   }
}


If this isn't the only place you need it, you could also use Burts code to extend eiter domain classes or the map itself via the ExpandoMetaClass.

This would centralize the functionality and keep your domain classes clean.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜