FetchType.EAGER 不要获取对象



我的实体:

@Entity
@NoArgsConstructor
public class Company {
@Id
@Getter
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "agent_id")
private Agent agent;
}

@Entity
@NoArgsConstructor
public class Agent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Getter
private Long id;
@Column(unique=true)
@Getter
private String name;
}

和问题方法

@Transactional
public void update(Company entity) {
Company existing = companyRepository.getOne(entity.getId());
//System.out.println(existing.getAgent().getName());
em.detach(existing);
System.out.println(existing.getAgent()); // => org.hibernate.LazyInitializationException: could not initialize proxy - no Session
}

最后一行导致 LazyInitializationException,如果我取消注释 System.out.println((,一切正常。所以它看起来像FetchType.LAZY。我做错了什么?

使用 findOne(( 方法而不是getOne((

方法findOne((- 内部调用实体管理器.getReference(...(。

getReference(( 调用它的结果是返回的对象,该对象是代理而不是实际的实体对象类型。因此,当您退出update((方法时,您将无法再调用代理。

我建议您阅读有关JPA代理如何工作以及如何使用Hibernate取消代理的信息

区别在于:

getOne()- 延迟加载

findOne()- 不是

最新更新