liveBook · Manning

Unique constraint

As explained in Java Persistence with Spring Data and Hibernate epub

A database constraint that requires each non-null value or combination of values in specified columns to be unique.

A unique constraint requires values in a column to occur at most once. In an object-relational mapping, it turns a foreign-key association into a database-enforced one-to-one relationship rather than relying only on application code. section 9.1.3 section 9.2.3

For a User–Address association, placing unique=true on @JoinColumn creates a SHIPPINGADDRESS_ID column with a unique constraint. No two users can reference the same address, while Hibernate can load the address lazily because the foreign-key value is available on the USERS row. section 9.1.3

One-to-one foreign-key mapping

@OneToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.PERSIST) @JoinColumn(unique = true) private Address shippingAddress; User john = new User("John Smith"); Address address = new Address("Flowers Street", "01246", "Boston"); john.setShippingAddress(address); userRepository.save(john); The mapping uses an ordinary foreign-key column instead of a shared primary key or special identifier generator. Saving the user transitively saves the linked address.

Apply the constraint with these considerations:

  • Use a unique foreign-key column when each source entity must reference a different target entity. section 9.1.3
  • Treat optionality carefully: nullable unique columns can allow multiple missing references, so they are typically not meaningful for enforcing a strict one-to-one relationship. section 9.1.3
  • Use a join-table unique constraint when an optional association should avoid nullable columns; constrain the appropriate foreign-key column to encode multiplicity. section 9.2.3

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains JPA configuration, lazy loading, nullability, and join-table alternatives without detailing database engine internals.
Examples
Demonstrates User.shippingAddress, SHIPPINGADDRESS_ID, Address entities, and an ITEM_BUYER join table.
What you can do after
Apply it via JPA annotations to enforce one-to-one associations and select suitable foreign-key or join-table mappings.
How it connects
Connects foreign keys, one-to-one associations, join columns, shared primary keys, lazy loading, and join tables.

Also explained in

Compare how 7 books explain unique constraint →

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.