2

Grails 2.2.1

My Simple domain:

class Article{
    SortedSet<Photo> photoGallery

    //helper method
    Photo getMainPhoto(){
        Photo mainPhoto = photoGallery.find{it.mainPhoto}
        return mainPhoto
    }
}

The one-to-many photoGallery is fetched lazily

I invoke the getMainPhoto method from the a .gsp view. The problem is that sometimes (not always) i get a LazyInitializationException error when trying to fetch the main photo from the lazy one-to-many photo gallery.

Why this happens occasionally and not each time i invoke that method? Is that normal? And how can i fix that, without making the relationship eagerly fetched?

Thanks

user711189
  • 4,383
  • 4
  • 30
  • 48

2 Answers2

0

Not sure, but I used to get the same error, when I was trying to access an object which is having nested objects inside a future, so sometimes in the concurrent executions due to lazy, all the nested domain objects wasn't getting fetched before using them.

problem can be avoided by accessing the same property on the block before using it on the view.

so if you add a print statement or something just below the line

Photo mainPhoto = photoGallery.find{it.mainPhoto}

then it should get loaded.

I am not sure but I think if you add it like this way:

Photo mainPhoto = photoGallery.find{it.mainPhoto}
println("mainPhoto=${mainPhoto}")

then it should render on the GSP page.

Saurabh Dixit
  • 633
  • 4
  • 16
0

The code that you gave, is it how you define your domain class, Article? Can you even use things like SortedSet? I thought you were required to use hasMany in all one-to-many situations if you wanted Grails to handle everything properly.

Another thing that may help: see if Article has an auto-generated helper method, something like getPhotoGallery. That is, do not just refer to the photoGallery directly.

If any of this helps, let us know. I am confused myself.

Sergey Orshanskiy
  • 6,794
  • 1
  • 46
  • 50