为什么我在 ManyToOne 关联中看不到休眠代理对象?

Why am I not seeing hibernate proxy objects in my ManyToOne associations?

根据休眠 docs,我的 @ManyToOne 关系默认应该有代理对象。但是,当我在 Eclipse 调试器("Variables" 视图)中查看扩展对象时,它看起来像字段变量是实体 class 中定义的基本类型的实例。此外,当我用 hibernate.show_sql=true 调用 session.get(type, id) 时,我可以看到对象上定义的所有 @ManyToOne 关系的 left outer join

为了让 Hibernate 为这些关系创建代理 classes/objects,是否需要做一些具体的事情?也许字节码增强?

引用休眠文档:

Lazy fetching for collections is implemented using Hibernate's own implementation of persistent collections. However, a different mechanism is needed for lazy behavior in single-ended associations. The target entity of the association must be proxied. Hibernate implements lazy initializing proxies for persistent objects using runtime bytecode enhancement which is accessed via the bytecode provider.

At startup, Hibernate generates proxies by default for all persistent classes and uses them to enable lazy fetching of many-to-one and one-to-one associations.

所有 @ManyToOne@OneToOne 关联都是 EAGER by default,这就是为什么当您获取根实体时它们被加入。

仅当关联未初始化时才使用代理。要让你的关联变得懒惰,你只需要添加 LAZY fetch 属性:

@ManyToOne(fetch = FetchType.LAZY)