Search code examples
javahibernatejpajpqlhibernate-mapping

How can I set Hibernate FetchType not to Eager or Lazy but to "none" so that it does NOT load the stuff itself?


I have an Hibernate class that has fields like this:

@OneToMany(
    orphanRemoval = true,
    mappedBy = "others",
    cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
private Set<AnotherEntity> otherEntities;

We have lazy loading on, so that it does not load everything at once. But I want to have it so that it does not load the stuff at all - if I want to load it, I will use a (Hibernate) query that gets all the necessary information. If I load only the main objects, nothing else should be loaded with them.

entity.getOtherEntities() should return null - even if there is data.

Is it somehow possible to achieve this?


Solution

  • There are several, exemplary options:

    1. You can use projection (an interface with getters and setters for fields you need to fetch). Here an example.
    2. You can pull up fields to superclass (using MappedSuperclass) and use it to fetch only the necessary data.
    3. Using EntityManager.createQuery you can specify fields using jpql, then only declared fields will be fetched.