2.5.2.11. One To One

When an entity A references a single entity B, and no other As can reference the same B, we say there is a one to one relation between A and B. In our sample model, Magazine has a one to one relation to Article through the Magazine.coverArticle field. No two magazines can have the same cover article.

JPA indicates one to one relations between entities with the OneToOne annotation. This annotation has the following properties:

  • Class targetEntity: The class of the related entity type. This information is usually taken from the field type.

  • String mappedBy: Names the field in the related entity that maps this bidirectional relation. We explain bidirectional relations in Bidirectional Relations above. Leaving this property unset signals that this is a standard unidirectional relation.

  • CascadeType[] cascade: Array of enum values defining cascade behavior for this field. We explore cascades in Cascade Type above. Defaults to an empty array.

  • FetchType fetch: Whether to load the field eagerly (FetchType.EAGER) or lazily (FetchType.LAZY). Defaults to FetchType.EAGER. See Fetch Type above for details on fetch types.

  • boolean optional: Whether the related object must exist. If false, this field cannot be null. Defaults to true.

The equivalent XML element is one-to-one which understands the following attributes:

  • name: The name of the field or property. This attribute is required.

  • target-entity: The class of the related type.

  • fetch: One of EAGER or LAZY.

  • mapped-by: The field that owns the relation. See Field and Property Metadata.

You may also nest the cascade element within a one-to-one element.