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
Use the entity relationship diagram to see Address as an independent entity that can be referenced by both User and Shipment. section 9.1
