Bidirectional relations are an essential part of data modeling.
Chapter 12, 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. Chapter 15, Mapping Metadata in the JDO
Overview explains how to do the same thing using the the
mapped-by
mapping attribute in JDO.
Kodo also allows you to define purely logical bidirectional
relations.
The
org.apache.openjpa.persistence.InverseLogical
annotation names a logical inverse in JPA metadata.
The inverse-logical
field extension names a logical inverse in JDO metadata.
Example 5.6. 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.
JPA:
import org.apache.openjpa.persistence.*; @Entity public class Magazine { @OneToOne private Photograph coverPhoto; ... } @Entity public class Photograph { @OneToOne @InverseLogical("coverPhoto") private Magazine mag; ... }
JDO:
<class name="Magazine"> <field name="coverPhoto"/> ... </class> <class name="Photograph"> <field name="mag"> <extension vendor-name="kodo" key="inverse-logical" value="coverPhoto"/> </field> ... </class>
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, Kodo behaves the same way. Kodo 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 Kodo 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 Kodo.
Set the
kodo.InverseManager
plugin property to
true
for standard management. Under this setting,
Kodo detects changes to either side of a bidirectional relation (logical
or physical), and automatically sets the other side appropriately on
flush.
Example 5.7. Enabling Managed Inverses
JPA XML format:
<property name="kodo.InverseManager" value="true"/>
JDO properties format:
kodo.InverseManager: 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, Kodo 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
.