我面临着LazyInitializationException
当我尝试访问分离实体的惰性 @ManyToOne 引用的 ID 时。我不想完全获取引用,但只需要 ID(它应该存在于原始对象中,以便以惰性/延迟的方式获取引用)。
EntityA ea = dao.find(1) // find is @Transactional, but transaction is closed after method exits
ea.getLazyReference().getId() // here is get exception. lazyReference is a ManyToOne relation and so the foreight key is stored in EntityA side.
换句话说,如何访问 LazyReference 的 ID(实际上存在于 EntityA 的初始选择中),而不实际获取整个 LazyReference?
当使用字段访问时,Hibernate 会处理getId()
方法与任何其他方法相同,这意味着调用它会触发代理初始化,从而导致LazyInitializationException
如果在分离的实例上调用。
要仅对 id 属性使用属性访问(同时保留对所有其他属性的字段访问),请指定AccessType.PROPERTY对于 id 字段:
@Entity
public class A {
@Id
@Access(AccessType.PROPERTY)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)