Hibernate Grails3-在控制器退出后防止不必要的select语句
请原谅这个做作的例子。我只是不明白为什么会发生这些选择 域对象:Hibernate Grails3-在控制器退出后防止不必要的select语句,hibernate,grails,gorm,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 = { } } 引导初始化: def ini
class Author {
String name
Location location
static mapping = {
location lazy: true //this is default, but set here to reduce confusion
}
static constraints = {
}
}
引导初始化:
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。根据我们在评论中的对话,它很可能与OSIV(视图中的开放会话)有关。解决方案是使用
.discard()
来确保hibernate不会检查是否有任何更改(例如脏检查)并且需要持久化。是否显示查看作者对象的位置属性的视图?如果是这样,那么当引用id
以外的任何内容时,这就是延迟获取关联。您可能也希望包含视图代码,以便我们能够更好地为您提供帮助。我不是在渲染Grails视图,只是“1”。这不是因为视图调用了代理域对象,可能是因为它获取了Hibernate缓存的关联。您是否尝试过在域类关联上强制延迟加载(我看到并回忆起映射)。是的,我尝试过。我将编辑原始帖子,以减少延迟加载带来的混乱。还有两件事需要尝试。使用load()
而不是get()
,在get()
之后,在实例上尝试添加discard()
。
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=?