Skip to content
Advertisement

EAP 7.3 JPA+Hibernate REST Serialization of Bidirectional ManyToOne relationship (NOT SPRING)

I come from a Payara/EclipseLink background where this just works out of the box. My contract requires me to use EAP which does not support EclipseLink.persistance and I always prefer the “provided” over adding libraries.

I am creating a very simple REST microservice with very simple relationships for my objects. However, when I try to access an object, I am getting a serialization error (specifics below).

ENTITY ONE

JavaScript

ENTITY TWO

JavaScript

REST END POINT FOR ENTITY ONE

JavaScript

StackTrace for REST Endpoint

JavaScript

The same error appears for the other side. When using EclipseLink, this just works out of the box, and I have tried a couple fo days but every example I have seen does not seem to address my specific issue.

For Clarity, here is the boundary code for ENTITY ONE

RESOURCE for ENTITY ONE

JavaScript

PERSISTANCE MANAGER FOR ENTITY ONE

JavaScript

Advertisement

Answer

Per spec, your manager EJB finds all entities and loads then into the returned List, but JPA defaults lists – such as classifications in your entity – as lazy loaded fields.

When your findAll method returns, there is no more transaction and the entities inside the lists became detached from the EntityManager. As such, the entity manager can’t to load the contents of each classifications field to allow serialization.

You may change the behavior of your entity manager using some internal properties or even define your classifications field as eager fetched, but this may induce performance problems when you use the TrainingCenterEntity without accessing the classifications field (the classifications will be retrieved from database every time you get a center).

Your best approach is changing your named query to use JOIN FETCH:

JavaScript

JOIN FETCH allows the JPA to eager fetch the contents of otherwise lazy loaded fields.

Please note that:

  • any findAll method tends to expose to much data; and
  • some implementations of JSON serialization libraries are not intelligent enough to detect circular relations, so your classification -> trainingcenter may cause a stack overflow if not properly annotated as ignored on serialization (@JsonIgnore in Jackson case).

Your code works without issues using EclipseLink probably because your entities weren’t static weaved prior execution. Some defaults configurations of EclipseLink also allows to load lazy fields in some different scenarios even with static weaved lazy loaded definitions. In hibernate, the weaving is called bytecode enhancement and it’s made automatically.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement