Bidirectional relations are an essential part of data modeling.
Chapter 13,
Mapping Metadata
in the JPA Overview explains how to
use the mappedBy
annotation attribute to form bidirectional
relations that also share datastore storage in JPA.
OpenJPA also allows you to define purely logical bidirectional relations. The
org.apache.openjpa.persistence.InverseLogical
annotation names a logical inverse in JPA metadata.
Example 5.9. Specifying Logical Inverses
Magazine.coverPhoto
and Photograph.mag
are
each mapped to different foreign keys in their respective tables, but form a
logical bidirectional relation. Only one of the fields needs to declare the
other as its logical inverse, though it is not an error to set the logical
inverse of both fields.
import org.apache.openjpa.persistence.*; @Entity public class Magazine { @OneToOne private Photograph coverPhoto; ... } @Entity public class Photograph { @OneToOne @InverseLogical("coverPhoto") private Magazine mag; ... }
Java does not provide any native facilities to ensure that both sides of a bidirectional relation remain consistent. Whenever you set one side of the relation, you must manually set the other side as well.
By default, OpenJPA behaves the same way. OpenJPA does not automatically propagate changes from one field in bidirectional relation to the other field. This is in keeping with the philosophy of transparency, and also provides higher performance, as OpenJPA does not need to analyze your object graph to correct inconsistent relations.
If convenience is more important to you than strict transparency, however, you
can enable inverse relation management in OpenJPA. Set the
openjpa.InverseManager
plugin property to true
for standard
management. Under this setting, OpenJPA detects changes to either side of a
bidirectional relation (logical or physical), and automatically sets the other
side appropriately on flush.
Example 5.10. Enabling Managed Inverses
<property name="openjpa.InverseManager" value="true"/>
The inverse manager has options to log a warning or throw an exception when it
detects an inconsistent bidirectional relation, rather than correcting it. To
use these modes, set the manager's Action
property to
warn
or exception
, respectively.
By default, OpenJPA excludes large
result set fields from management. You can force large result set fields
to be included by setting the ManageLRS
plugin property to
true
.
Example 5.11. Log Inconsistencies
<property name="openjpa.InverseManager" value="true(Action=warn)"/>