Skip to content

Ignore missing entities when lazy loading is enabled, if (newly added) Feature.WRITE_MISSING_ENTITIES_AS_NULL is enabled #125

@mobreza

Description

@mobreza

I have a fairly odd JPA mapping where the owning entity has a "potential" identifier to another entity in otherIndex:

...
private Long otherIndex;
	
@ManyToOne(cascade = {}, fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "otherIndex", nullable = true, insertable = false, updatable = false, foreignKey = @javax.persistence.ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))
@JsonView({ JsonViews.Protected.class })
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private SomeOther someOther;
...

This mapping allows for SomeOther to perhaps exist in the database and if it does, it's properly serialized (when using disable(Feature.FORCE_LAZY_LOADING)). Sometimes there's no record with otherIndex in SomeOther.

We have two serializers: one for Spring MVC with lazy loading disabled:

hibernateModule.disable(Feature.FORCE_LAZY_LOADING);

and one for serializing to JSON for Elasticsearch indexing with lazy loading enabled:

hibernateModule.enable(Feature.FORCE_LAZY_LOADING);

The MVC serializer behaves as expected, but the FORCE_LAZY_LOADING on ES serializer dies when there's no record of "referenced" entity with:

Caused by: javax.persistence.EntityNotFoundException: Unable to find ............SomeEntity with id 26305216
	at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:183)
	at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:262)
	at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:176)
	at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
	at com.fasterxml.jackson.datatype.hibernate4.HibernateProxySerializer.findProxied(HibernateProxySerializer.java:202)
	at com.fasterxml.jackson.datatype.hibernate4.HibernateProxySerializer.isEmpty(HibernateProxySerializer.java:96)

I'd prefer if this behavior was configurable and would default to null when EntityNotFoundException is thrown in com.fasterxml.jackson.datatype.hibernate4.HibernateProxySerializer#findProxied method.

Could we have something along the lines of .enable(WRITE_MISSING_ENTITIES_AS_NULL)?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions