Search code examples
hibernategrailsgrails-orm

Grails 3 - prevent unnecessary select statements after controller exits


Please excuse the contrived example. I just can't figure out why these selects are happening.

Domain objects:

class Author {
    String name
    Location location

    static mapping = {
        location lazy: true //this is default, but set here to reduce confusion
    }

    static constraints = {
    }
}

...

class Location {
    String address
    static hasOne = [longLat : LongLat]

    static constraints = {
    }
}

...

class LongLat {
    String longitude
    String latitude

    static belongsTo = [location:Location]

    static constraints = {
    }
}

...

Bootstrap init:

def init = { servletContext ->
        Location loc = new Location(address: '123 asdf dr', longLat: new LongLat(longitude: 0.5, latitude: 0.5)).save(flush:true)
        new Author(name: 'Author Name', location: loc).save(flush:true)
    }

...

Action from controller:

def index() {
    println "Start Controller"
    Author.get(1)
    render '1'
    println "End Controller"
}

I have logging turned on:

logSql: true
formatSql: true

The output:

Grails application running at http://localhost:8080 in environment: development
Start Controller
Hibernate:
    select
        this_.id as id1_0_0_,
        this_.version as version2_0_0_,
        this_.location_id as location3_0_0_,
        this_.name as name4_0_0_
    from
        author this_
    where
        this_.id = ?
End Controller
Hibernate:
    select
        location0_.id as id1_1_0_,
        location0_.version as version2_1_0_,
        location0_.address as address3_1_0_
    from
        location location0_
    where
        location0_.id=?
Hibernate:
    select
        longlat0_.id as id1_2_0_,
        longlat0_.version as version2_2_0_,
        longlat0_.latitude as latitude3_2_0_,
        longlat0_.location_id as location4_2_0_,
        longlat0_.longitude as longitud5_2_0_
    from
        long_lat longlat0_
    where
        longlat0_.location_id=?

Why are these last two selects happening, and how can I stop them without resorting to HQL?

I'm using Grails 3.2.3.


Solution

  • Per our conversation in comments it's turned out to most likely be related to the OSIV (open session in view). The solution is to use .discard() to ensure that hibernate won't check to see if anything has changed (e.g. dirty checking) and needs to be persisted.