Disabling all implicit/automatic fetching

Hello, thanks in advance for any answers on this.

I’m using hibernate and I want to disable any form of lazy loading AND eager fetching.

I want to require that for a property, or collection from a separate table to be loaded, that the user must specifically request that either through a JPQL join, or an EntityGraph. If the object, or collection hasn’t been loaded then a LazyInitializationException, or some other exception can be thrown.

The motivation for this is I don’t want that level of magic and I want it to be clearer in the code what relations are being fetched. I don’t want to have to look at the queries being executed in logs, or install metrics or libraries to detect extra queries being run. I don’t want queries to ever be run invisibly when a property is accessed.

Ideally, I would be able to globally configure this and not have to annotate every property as lazy or eager because it is really neither.

Does such a configuration exist, or is there any way to achieve this in hibernate today?

I’m aware that there are some workarounds, such as using projections, or managing the Session scope very explicitly. Projections reduce the productivity of hibernate greatly if they were to be used exclusively. Managing session scope is also something that would need to be enforced in code reviews, instead of just being set as a configuration in one place.

In other ORMs, such as Entity Framework Core, the user is required to explicitly include relations, unless they specifically go and install their proxy package and configure it. This is essentially what I’m looking to achieve, complete removal of proxying.

No, there is nothing like that.

You can use a tool like Blaze-Persistence Entity-Views on top of JPA/Hibernate to make your life easier in this regard, as it implements exactly what you are looking for, but through types so that you don’t even have the possibility of accidentally calling a method that could fail because state wasn’t initialized.

I see. Thanks for the response!

I really want to avoid hidden loading of properties and collections even being possible at all, so I’m not sure that projections are quite what I’m looking for. Those would need to be enforced by code review etc. I’ll look into that a bit more, thanks for the tip.

Out of curiosity, do you think it would be possible to implement a configuration option that disables proxying, or would that be something orthogonal to hibernate’s design?

There is no hidden loading. You request a projection and you retrieve exactly that data as specified by the type. No lazy loading or cycles possible, so the code review for such a solution would be limited to figuring out if the data that is modeled in the types really is necessary.

No, that’s not possible.