Search code examples
javahibernategrailsrelational-databasegrails-orm

Grails/GORM dynamic finder to get the domain by its relation ID instead of relation object itself


grailsVersion=3.2.9, gormVersion=6.0.10

Say, we have two grails domains:

class A {
   int id
   B b
}

class B {
   int id
}

Now, if I have an ID of some B in my code(say I have that ID in an enum), to get an instance of A by ID of B using GORM dynamic finder the only way is the following:

A.findByB(B.get(bId))

which does cause an additional query to get the B instance and that is not ideal.

So is there any way, maybe some Grails/GORM plugin, adding a support for the following:

A.findByBId(bId)

Solution

  • Use A.findByB(B.load(bId)) to avoid fetching the B object.

    http://docs.grails.org/latest/ref/Domain%20Classes/load.html