liveBook · Manning

@OneToOne

As explained in Java Persistence with Spring Data and Hibernate epub

@OneToOne is a Jakarta Persistence annotation that declares an entity-valued property as a one-to-one association.

@OneToOne declares an entity-valued property as a one-to-one association. Configure optionality, cascading, fetching, and the database strategy on the association. section 9.1.1

Choose the association strategy according to lifecycle and optionality:

  • Use a shared primary key when one entity is always stored first and can provide the other entity's identifier. section 9.1.1
  • Use a foreign key association in other cases. section 9.1.4
  • Use an intermediate join table when the one-to-one association is optional. section 9.1.4

Shared primary key: User and Address

Map User.shippingAddress with @OneToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.ALL) and @PrimaryKeyJoinColumn. Persist Address first, copy address.getId() into User, then save User inside a transaction. section 9.1.1

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains shared-primary-key and join-table mappings, identifier coordination, lazy loading, uniqueness, and transactional tests; it only summarizes foreign-key selection.
Examples
Uses User and Address shipping data, plus Shipment and Item links, with Java mappings, uniqueness constraints, persistence calls, and tests.
What you can do after
Apply it via Jakarta Persistence and Spring Data JPA to configure one-to-one mappings and persist linked entities transactionally.
How it connects
Connects one-to-one associations with shared primary keys, foreign keys, join tables, cascading, lazy loading, identifiers, and transactions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.