Skip to content
Anjunar/ DOCS

Graphs and references

JPA entity graphs decide how deep an entity is written and read. References arrive by ID, and both sides of a relation are kept in sync.

Entity graphs

The same graph for fetching and mapping

Pass an EntityGraph and, for classes that implement EntityProvider, only the attributes of the graph and its subgraphs are serialized. The query that loaded the entity and the JSON describe the same shape.

scala
val graph = entityManager.getEntityGraph("Article.full") val article = entityManager.find(classOf[Article], id, java.util.Map.of("jakarta.persistence.fetchgraph", graph)) JsonMapper.serialize(article, TypeResolver.resolve(classOf[Article]), graph, inject)

@JsonbGraphProperty(transitive = true) includes a property whatever the graph says. A property named links is always included, for hypermedia links.

Writing

Graphs limit updates too

When the target is a persisted entity (version above -1) and a graph is given, only its attributes are written. A client cannot reach deeper than the graph that was sent to it.

scala
trait EntityProvider { def id: UUID def version: Long // -1 for a new, unsaved entity }
References

By ID, through the EntityLoader

A related object that the target does not hold yet is resolved by the "id" in its JSON. The loader returns the managed instance, which is then set as the reference; unknown IDs create a new instance.

scala
val loader: EntityLoader = (id, clazz) => entityManager.find(clazz, id)
json
{"title": "Graphs", "author": {"id": "3f1c9a52-7c0e-4f6b-9b1d-2a8e5c7d4f10"}}
Relations

Both sides stay consistent

After setting a JPA relation, the mapper updates its other side: the owning side named by mappedBy, the inverse collection of a @ManyToOne, or the partner of a @ManyToMany.

@OneToMany

Children get their parent

Each element's mappedBy property is set to the owner.

@ManyToOne

The parent gets the child

The owner is added to the inverse collection of the new parent.

@OneToOne · @ManyToMany

Partners point back

The partner's property or collection is pointed at the owner.