Ehcache Hibernate 2nd-level cache - Element for key is Null and N+1 query issue

Most likely this happens because, by default, @ManyToOne and @OneToOne associations are using FetchType.EAGER.

So, in your case, you have an entity that was cached. But when you fetch it, it tries to load all EAGER associations as well, which are not cached, like:

  • Employee
  • Departement
  • Address

To fix it, you have to options:

  1. Either you set all to FetchType.LAZY for all these @ManyToOne and @OneToOne associations

     @MnyToOne(fetch = FetchType.LAZY)
     private Employee employee;
    
  2. Or, you cache all these entities as well, meaning that you need to provide the Hibernate @Cache annotation which provides the cache concurrency strategy:

     @Entity(name = "Employee")
     @Cacheable
     @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
     public class Employee {
         ....
     }