Hibernate:session.load方法何时返回代理对象?
session.load() return a proxy? Great question! Let's break down the key scenarios where session.load() will hand you a proxy instead of a real, initialized entity instance:
When the target entity isn't in the current Session's first-level cache (Persistent Context)
This is the most common case. By design,session.load()is optimized for lazy loading. If the entity with the specified ID isn't already cached in your active Session, Hibernate won't hit the database immediately. Instead, it returns a lightweight proxy that only holds the entity's ID. The actual database query to load the full entity data won't run until you call a method on the proxy that's not related to getting the ID (likegetUsername()orgetEmail()).Example:
// Returns a proxy immediately—no DB query yet User user = session.load(User.class, 123L); // Now we access a non-ID property: triggers DB query to initialize the proxy String userEmail = user.getEmail();When loading a lazily fetched associated entity
If you're usingsession.load()to fetch an entity that's linked via a lazy association (like a@ManyToOneor@OneToOnewithfetch = FetchType.LAZY), Hibernate will return a proxy even if you explicitly callload(). This aligns with the lazy loading strategy for associations—Hibernate avoids loading related entities until absolutely necessary.When the entity isn't present in the second-level cache (if enabled)
If you have a second-level cache set up for your entity,session.load()will first check the first-level cache, then the second-level cache. If neither has the entity, it falls back to returning a proxy, just like the first scenario. The proxy will be initialized (and the entity added to both caches) once you access a non-ID property.
It's also worth noting when you won't get a proxy: if the entity is already in the current Session's first-level cache (e.g., you fetched it earlier with session.get() or saved it in the same Session), session.load() will return the existing real entity instance directly—no proxy involved.
内容的提问来源于stack exchange,提问作者Vicky

