Grails gets any of the kids at hasMany

I have a domain class that has many other domain classes. I want any of the children, and I don't care. Example

class MyDomainClass { static hasMany = [thingies:OtherDomainClass] } 

I can do it stupidly like:

 def findOne myInstance.thingies.each{ findOne=it } 

But is there a better way:

 def findOne = myInstance.thingies.grabTheMostConvenientOne() 
+6
source share
1 answer

thingies is a collection, so you have everything from Collection at your disposal.

In a simple way, you can do this:

 def one = myInstance.thingies.asList().first() 

However, you probably want to make sure that the collection does have some elements. The documentation does not explicitly state that first() throws an IndexOutOfBoundsException if the list is empty, but I feel it is still possible. If this happens, you probably want to:

 def one = myInstance.thingies.size() > 0 ? myInstance.thingies.asList().first() : null 

Or, if you want to be super-concise due to some readability, you can use this approach ( courtesy of John Wagenleitner) :

 def one = myInstance.thingies?.find { true } 
+9
source

Source: https://habr.com/ru/post/891498/


All Articles