Question

Constantly faced with a problem when I need to compare and manipulate objects that reference other objects. For example:

Class Student {
...
String Name
Integer Age
...
}

Class Stuff {
...
Student student
...
}

When I invoke an instance of Stuff (Stuff.get (id)/load(id)) and will access the Name, Age and other attribute I see in debug mode (stuff .name = null, they're like 'null' although they are not null. It command when analyzing values ​​of these attributes (stuff .name == "pen") error occurs.

I need to invoke the instances and compare their values ​​to execute business rules, but do not know how to resolve this issue.

I read something about the inclusion in the configuration Stuff Mapping 'student lazy: false' for all the time you need to load the instance ofstuff , also charge the Student, but that in addition to overload the memory (since stuff is a Domain Great) would solve this case being the only solution to put all references as 'lazy: false' which would slow the application just to make a simple comparison.

Does anyone know how to invoke instances (Stuff), automatically invoking the attribute to be working (student) just to make the comparison of data, without using the 'student lazy: false' that invokes the data at all times?...

Using Grails 2.2.0 e o Groovy 2

Was it helpful?

Solution

Stuff don't have a property called name so you should get MissingPropertyException calling stuff.name. This has nothing to do with the lazy or eager relationship.

You can check the definition of a lazy relationship in the documentation and also the difference between the types of fetch.

To access the name property you need to access the student property before:

Stuff instance = Stuff.get(id)
println instance.student.name //this, if lazy, will trigger a new database query.

If you know that your code will access the Student instance by the relation with Stuff you could fetch both in one database access (eager and not lazy):

Stuff instance = Stuff.withCriteria {
  eq('id', id)
  fetchMode("student", FetchMode.JOIN)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top