Preprocessing fields with database queries when storing entities

When storing entities, I sometimes need to do some processing in the getter of an entity’s field, as the data is not readily available. (This has performance reasons - some data is computed lazily, eagerly is not an option unfortunately). Now it can happen that it is required to make a database query in said getter, to generate the relevant data.

The result is an endless recursion as Hibernate tries to flush the currently on-going persist transaction before executing the fetch query. The flush operation, eventually ends up in the same getter method as before, again executing the fetch query.

One option is to pre-process every applicable field for all entities to be stored and only perform the persist operation afterwards, eliminating the need to perform any fetch queries while persisting. This option is not really available here, however, as the data to be stored involves a lot of cascades with many different classes, effectively making it near-impossible to know in advance what will be persisted thanks to the cascades.

I’ve also considered setting up a second read-only database connection (+EntityManager) which I can fetch required entities from while storing via the first connection. However then I’d surely have the issue of detached entities, correct?

What would the best way to approach this issue be?

Thank you!

P.S.: A large reason for doing this in the first place is to avoid duplicate database entries. Say we have two instances of Foo, which are identical, then only one of those should be stored in the database. Many identical instances may exist, however, and be referenced by entities that will all be stored (Checking the database every time a new instance of Foo is created would cause too much overhead, so it is done when storing the entities in the DB). If there is a better way to solve the root problem than to check the database before storing Foo instances, that would also help :slight_smile: