java - LazyInitializationException: id to load is required for loading - Stack Overflow

I'm facing a LazyInitializationException when I'm trying to unproxy a relation having FetchTy

I'm facing a LazyInitializationException when I'm trying to unproxy a relation having FetchType.LAZY. this issue is random and cannot be reproduced, I happened to find the next exception in the server logs:

Caused by: .hibernate.LazyInitializationException: id to load is required for loading
at .hibernate.proxy.AbstractLazyInitializer.permissiveInitialization(AbstractLazyInitializer.java:233) ~[hibernate-core-5.4.32.Final.jar!/:5.4.32.Final]
at .hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167) ~[hibernate-core-5.4.32.Final.jar!/:5.4.32.Final]
at .hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:310) ~[hibernate-core-5.4.32.Final.jar!/:5.4.32.Final]
at com.xyz.Utility.unwrapProxy(Utility.java:50) ~[implementation.jar:?]

The same process is executed every day but it only fails once or twice a month. The is the code of unproxy method:

if (object instanceof HibernateProxy) {
        HibernateProxy hibernateProxy = (HibernateProxy) object;
        LazyInitializer initializer = hibernateProxy.getHibernateLazyInitializer();
        return initializer.getImplementation(); //this is line 50 in the exception
    }

I copied this from Vlad's thread

I don't have a reproducible scenario, I tried to debug the issue, I found out that a proxy object cannot have a LazyInitializer with Id null when creating the object which means that the object is made with a valid identifier. Also, there is no other exceptions logged at the time when this exception occured.

My question: What can cause the LazyInitializer registered on a hibernate proxy to have an Id null?

EDIT: Nested exception:

2025-01-24 07:00:35,710 ERROR [.hibernate.proxy.AbstractLazyInitializer] (default-threads - 30) Initialization failure [com.xyz.MyEntity#null]: java.lang.IllegalArgumentException: id to load is required for loading
at .hibernate.event.spi.LoadEvent.<init>(LoadEvent.java:96) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.event.spi.LoadEvent.<init>(LoadEvent.java:64) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.internal.SessionImpl.recycleEventInstance(SessionImpl.java:1080) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.internal.SessionImpl.immediateLoad(SessionImpl.java:1004) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.proxy.AbstractLazyInitializer.permissiveInitialization(AbstractLazyInitializer.java:214) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:310) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at com.xyz.Utility.unwrapProxy(Utility.java:50) ~[implementation.jar:?]

I'm facing a LazyInitializationException when I'm trying to unproxy a relation having FetchType.LAZY. this issue is random and cannot be reproduced, I happened to find the next exception in the server logs:

Caused by: .hibernate.LazyInitializationException: id to load is required for loading
at .hibernate.proxy.AbstractLazyInitializer.permissiveInitialization(AbstractLazyInitializer.java:233) ~[hibernate-core-5.4.32.Final.jar!/:5.4.32.Final]
at .hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167) ~[hibernate-core-5.4.32.Final.jar!/:5.4.32.Final]
at .hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:310) ~[hibernate-core-5.4.32.Final.jar!/:5.4.32.Final]
at com.xyz.Utility.unwrapProxy(Utility.java:50) ~[implementation.jar:?]

The same process is executed every day but it only fails once or twice a month. The is the code of unproxy method:

if (object instanceof HibernateProxy) {
        HibernateProxy hibernateProxy = (HibernateProxy) object;
        LazyInitializer initializer = hibernateProxy.getHibernateLazyInitializer();
        return initializer.getImplementation(); //this is line 50 in the exception
    }

I copied this from Vlad's thread

I don't have a reproducible scenario, I tried to debug the issue, I found out that a proxy object cannot have a LazyInitializer with Id null when creating the object which means that the object is made with a valid identifier. Also, there is no other exceptions logged at the time when this exception occured.

My question: What can cause the LazyInitializer registered on a hibernate proxy to have an Id null?

EDIT: Nested exception:

2025-01-24 07:00:35,710 ERROR [.hibernate.proxy.AbstractLazyInitializer] (default-threads - 30) Initialization failure [com.xyz.MyEntity#null]: java.lang.IllegalArgumentException: id to load is required for loading
at .hibernate.event.spi.LoadEvent.<init>(LoadEvent.java:96) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.event.spi.LoadEvent.<init>(LoadEvent.java:64) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.internal.SessionImpl.recycleEventInstance(SessionImpl.java:1080) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.internal.SessionImpl.immediateLoad(SessionImpl.java:1004) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.proxy.AbstractLazyInitializer.permissiveInitialization(AbstractLazyInitializer.java:214) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at .hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:310) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at com.xyz.Utility.unwrapProxy(Utility.java:50) ~[implementation.jar:?]
Share Improve this question edited Mar 3 at 6:58 Kakashi asked Mar 3 at 5:30 KakashiKakashi 3092 silver badges12 bronze badges 2
  • 1 You should have log entry from LOG.error( "Initialization failure [" + entityName + "#" + id + "]", e ); it contains nested exception, Can you post it. It should have information about real cause. – talex Commented Mar 3 at 6:27
  • Hello @talex i edited the original post and added the nested exception. – Kakashi Commented Mar 3 at 6:58
Add a comment  | 

1 Answer 1

Reset to default -1

I think the most likely cause of the error is multithreading issues, where one thread closes the Session while another attempts to unproxy it. This explains the rarity of the error. Before calling getImplementation(), check if initializer.getSession() is null:

log.info("Thread: {}, Session is open: {}", Thread.currentThread().getName(), initializer.getSession() != null);

If null, ensure that the proxy is being accessed within the same transaction, or initialize the object beforehand:

Hibernate.initialize(proxyObject);

Caching issues (Hibernate L2 Cache or Spring Cache) could also be a cause, so try disabling it:

spring.jpa.properties.hibernate.cache.use_second_level_cache=false

UPDATE:

The second-level cache (L2 Cache) can be problematic if it stores an incomplete or outdated proxy object, for example, one without a valid id. When Hibernate loads a lazy association, it first checks the cache, and if it contains a corrupted proxy, attempting to unproxy it may result in the following error:

LazyInitializationException: id to load is required for loading

This explains why the error occurs randomly, as the cache updates at different times. However, not all lazy associations are cached by default. Hibernate does not cache them unless explicitly configured via @Cache or if a specific caching provider (such as Ehcache or Infinispan) is used. This issue is more likely if caching is enabled for associations that frequently change, and the cache does not properly update when the data is modified.

Instead of disabling caching entirely, first, exclude lazy associations from caching, as they are often the main issue. You can do this using the following annotation:

@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
@Cache(usage = CacheConcurrencyStrategy.NONE) // Disable caching only for this association
private List<Child> children;

If the issue persists, temporarily disable L2 Cache entirely to verify whether it is the root cause:

spring.jpa.properties.hibernate.cache.use_second_level_cache=false

If the error disappears, it confirms that caching is causing the problem, and the caching strategy should be adjusted. Instead of completely disabling caching, you can use a weak synchronization strategy to allow updates while maintaining some level of caching:

@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)

However, NONSTRICT_READ_WRITE does not guarantee immediate cache updates, meaning there is still a chance that an outdated proxy could be retrieved if the entity has changed in the database but the cache was not refreshed. If the problem persists even after switching to this strategy, consider forcing the object to refresh before unproxying it:

entityManager.unwrap(Session.class).refresh(proxyObject);

Additionally, since lazy associations are loaded without a transaction, make sure that the object is fully initialized before using it. If the entity is retrieved via DTOs, Projections, or GraphQL, ensure that Hibernate properly initializes the proxy before any operations:

Hibernate.initialize(proxyObject);

If disabling caching does not solve the issue, the root cause might not be caching but rather the way lazy loading is handled without an active session. In such cases, review the entity loading mechanism and ensure that lazy associations are initialized correctly before being accessed.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745108806a4611720.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信