liveBook · Manning

Shared primary key value

As explained in Java Persistence with Spring Data and Hibernate epub

A shared primary key one-to-one association is a relationship in which the dependent entity uses the referenced entity's primary-key value as its own identifier.

A shared primary key one-to-one association stores related rows with identical primary-key values. In the shipping-address model, User and Address are separate entities, while User uses the Address identifier as its own. section 9.1 section 9.1.1

The mapping uses @OneToOne, optional=false, cascade= CascadeType.ALL, and @PrimaryKeyJoinColumn. User has no identifier generator, so Address must be saved first and its generated identifier copied to User. section 9.1.1 section 9.1.1

A practical persistence sequence is:

  • Create and save the Address so its generated identifier becomes available. section 9.1.1
  • Construct the User with the Address identifier, set shippingAddress, and save the User. section 9.1.1 section 9.1.1
  • Run the operations transactionally through a Spring service configured with transaction management. section 9.1.1

Hibernate offers a foreign primary-key generator that reverses the dependency: Address obtains its identifier from its associated User. With mappedBy and CascadeType.PERSIST, saving User persists Address transitively without manually copying identifiers. section 9.1.2 section 9.1.2

Manual shared-key persistence

Address address = new Address("Flowers Street", "01246", "Boston"); addressRepository.save(address); User john = new User(address.getId(), "John Smith"); john.setShippingAddress(address); userRepository.save(john); section 9.1.1

Figure 9.1 Address as an entity with two associations, supporting shared references

Use the entity relationship diagram to see Address as an independent entity that can be referenced by both User and Shipment. section 9.1

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains annotations, schema constraints, identifier ordering, transactions, and Hibernate generation, but defers broader one-to-one alternatives to comparison.
Examples
Demonstrates User and Address mappings, manual identifier copying, a Hibernate foreign generator, and an Address shared by User and Shipment.
What it assumes
Assumes basic Java, entity, repository, and Spring configuration knowledge while introducing one-to-one annotations and identifier coordination.
What you can do after
Build it from scratch with JPA annotations, Spring transactions, explicit identifier ordering, or Hibernate's foreign generator.
How it connects
Connects one-to-one associations with entity identity, cascading, transactions, foreign-key associations, and join tables.

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.