Hibernate 一对一:getId() 不获取整个对象 [英] Hibernate one-to-one: getId() without fetching entire object
本文介绍了Hibernate 一对一:getId() 不获取整个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在不加载整个对象的情况下获取一对一关系的 id.我想我可以使用延迟加载来做到这一点,如下所示:
I want to fetch the id of a one-to-one relationship without loading the entire object. I thought I could do this using lazy loading as follows:
class Foo {
@OneToOne(fetch = FetchType.LAZY, optional = false)
private Bar bar;
}
Foo f = session.get(Foo.class, fooId); // Hibernate fetches Foo
f.getBar(); // Hibernate fetches full Bar object
f.getBar().getId(); // No further fetch, returns id
我希望 f.getBar() 不 触发另一个获取.我希望 hibernate 给我一个代理对象,它允许我调用 .getId() 而不实际获取 Bar 对象.
I want f.getBar() to not trigger another fetch. I want hibernate to give me a proxy object that allows me to call .getId() without actually fetching the Bar object.
我做错了什么?
推荐答案
使用属性访问策略
代替
@OneToOne(fetch=FetchType.LAZY, optional=false)
private Bar bar;
使用
private Bar bar;
@OneToOne(fetch=FetchType.LAZY, optional=false)
public Bar getBar() {
return this.bar;
}
现在一切正常!
如果您调用任何不是标识符获取方法的方法,则会初始化代理.但它只适用于使用属性访问策略.记住它.
A proxy is initialized if you call any method that is not the identifier getter method. But it just works when using property access strategy. Keep it in mind.
这篇关于Hibernate 一对一:getId() 不获取整个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文