0

What is the most efficient solution to get the status attribut value from a ClassD instance by having its name attribut value and starting from the ClassA instance?

I can use on loop in each list, but I think there is a better solution by using a create criteria

Class ClassA {
    static hasMany = [CLassBList:ClassB]
}


Class ClassB {
   static hasMany = [CLassCList:ClassC]
   static belongsTo = [ClassA]
}


Class ClassC {
    static hasMany = [CLassDList:ClassD]
    static belongsTo = [ClassB]
 }


Class ClassD {
    String name
    String status
    static belongsTo = [ClassC]
}
Jils
  • 783
  • 5
  • 12
  • 32

1 Answers1

1

Am assuming (although your code doesn't mention it) that you have some criteria on ClassA that you want to search on, then you can use a createCriteria like this:

def c = ClassD.createCriteria()
def results = c.list () {
  projections { property('status') }
  classC {
    classB {
      classA {
        eq('classAProperty', someClassAValue)
      }
    }
  }
}

Use .get() rather than .list() if you expect only 1 result, then you might also want an order() clause.

Remove the projections if you want the entire ClassD returned, then deal with as you see fit.

shuttsy
  • 1,585
  • 2
  • 19
  • 34
  • In your code classC, classB and classA are intances or Classes? – Jils Sep 16 '15 at 10:57
  • They are properties/labels to the parent class. I usually specify belongsTo like this: static belongsTo = [classC: ClassC] – shuttsy Sep 16 '15 at 11:43
  • I didn't specify belongsTo like you but like this: static belongsTo = [ClassC]. The createCritea should to be changed as a consequence? – Jils Sep 16 '15 at 12:06
  • I'd try classC first as it might be a Grails convention when a label isn't provided it gives you the class name in camelcase. As a tip, camelcase are usually used for instances/properties, whereas capitialised is the Class. The same applies to your hasMany: i'd specify those relationships as: static hasMany = [classBs:ClassB]. Try it and see what works. In my experience, Grails gives you good error messages when the criteria fails. – shuttsy Sep 16 '15 at 13:38
  • I have this error: "No signature of method: myapp.UserController.classc() is applicable for argument types: (myapp.UserController$_test_closure1_closure3) values: [myapp.UserController$_test_closure1_closure3@32f1277]" – Jils Sep 16 '15 at 13:59