Grails 3 - 在控制器退出后防止不必要的select语句

时间:2017-01-30 00:13:33

标签: hibernate grails gorm

请原谅人为的例子。我无法弄清楚为什么会发生这些选择。

域对象:

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)
    }

...

来自控制器的行动:

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

我已开启日志记录:

logSql: true
formatSql: true

输出:

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=?

为什么最后两个选择发生了,如何在不诉诸HQL的情况下阻止它们?

我正在使用Grails 3.2.3。

1 个答案:

答案 0 :(得分:0)

根据我们在评论中的对话,结果很可能与OSIV(视野中的开放会话)有关。解决方案是使用.discard()来确保hibernate不会检查是否有任何更改(例如脏检查)并且需要保留。