Announcement Announcement Module
Collapse
No announcement yet.
Eager fetching on a one-to-one relationship causing extra selects Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Eager fetching on a one-to-one relationship causing extra selects

    Hello!

    I've run across a strange GORM issue that manifests itself while running the application, but does NOT happen when running the same code in a grails shell. I have a typical one-to-one relationship similar to below with eager fetching by the parent object on a one-to-one child:

    class Parent {
    Child child

    static mapping = {
    child fetch:'join'
    }
    }

    class Child {
    static belongsTo = [parentalUnit:Parent]
    }

    According to the hibernate sql logging, whenever I retrieve a Parent by id I'm also retrieving the same Parent by child_id, caused by the Child object retrieving the Parent. This overhead is especially bothersome when retrieving a list of Parents. The weird thing is that when I start up a grails shell and retrieve a Parent, I don't see any subsequent retrievals made on the Child's behalf.

    Can someone explain what's going on? I want to suppress the Child from retrieving it's Parent if I'm getting a Parent.

    Thanks,

    Jaime

  • #2
    This is because Grails doesn't technically treat the relationship as a one-to-one, so it doesn't know 'parent' is a back-reference. You can get the behaviour you want by modifying the Parent class to look like this:

    Code:
    class Parent {
        static hasOne = [ child: Child ]
    }
    This affects which table contains the foreign key, but hopefully that's not an issue for you. If your app is in production, then you will have to migrate the database.

    Hope that helps.

    Comment

    Working...
    X