@ManyToOne 引用的 getId() 上的 LazyInitializationException

Moh*_*sen 1 java hibernate lazy-loading many-to-one lazy-initialization

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.
Run Code Online (Sandbox Code Playgroud)

换句话说,如何在不实际获取整个 LazyReference 的情况下访问 LazyReference 的 ID(实际上存在于 EntityA 的初始选择中)?

Dra*_*vic 5

当使用字段访问时,Hibernate 将getId()方法视为与任何其他方法相同,这意味着调用它会触发代理初始化,从而导致LazyInitializationExceptionif 在分离的实例上调用。

要仅对 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;
  }
}
Run Code Online (Sandbox Code Playgroud)