@OneToOne
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A customer has one wallet, and no customer may have two. The tables can enforce that in two ways, and the choice changes both the mapping and its speed.
A foreign-key one-to-one: customer and wallet
A foreign-key one-to-one is a normal foreign key column with a UNIQUE constraint, such as wallets.customer_id, so each customer has at most one wallet. JPA maps it with @OneToOne, and the side with the column owns the link.
A wallet belongs to one customer. The two tables below store that kind of link in two different ways.
CREATE TABLE wallets ( -- foreign-key one-to-one wallet_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, customer_id INT NOT NULL, balance DECIMAL(10,2) NOT NULL DEFAULT 0.00, CONSTRAINT uq_wallets_customer UNIQUE (customer_id), FOREIGN KEY (customer_id) REFERENCES customers (customer_id));CREATE TABLE loyalty_cards ( -- shared primary key customer_id INT NOT NULL PRIMARY KEY, card_number VARCHAR(16) NOT NULL, points INT NOT NULL DEFAULT 0, FOREIGN KEY (customer_id) REFERENCES customers (customer_id));Example 1 · Wallet.java: the owning side with a unique foreign key
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
package com.shoplite.lab.customer;
import java.math.BigDecimal;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.FetchType;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.JoinColumn;import jakarta.persistence.OneToOne;import jakarta.persistence.Table;
@Entity@Table(name = "wallets")public class Wallet {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "wallet_id") private Integer id;
@OneToOne(fetch = FetchType.LAZY) // owning side: holds customer_id @JoinColumn(name = "customer_id", unique = true) // UNIQUE makes it one-to-one private Customer customer;
private BigDecimal balance;
protected Wallet() { }
public Wallet(Customer customer) { this.customer = customer; this.balance = BigDecimal.ZERO; }
public Integer getId() { return id; } public Customer getCustomer() { return customer; } public BigDecimal getBalance() { return balance; }}
interface WalletRepository extends JpaRepository<Wallet, Integer> {
Optional<Wallet> findByCustomerId(Integer customerId);}
// CustomerLabService.walletOf, called for customers 2 and 3@Transactional(readOnly = true)public void walletOf(int customerId) { String balance = wallets.findByCustomerId(customerId) .map(w -> w.getBalance().toString()) .orElse("no wallet"); System.out.println("Customer " + customerId + ": " + balance);}DEBUG SQL - select w1_0.wallet_id,w1_0.balance,w1_0.customer_id from wallets w1_0 where w1_0.customer_id=? Customer 2: 1250.50 DEBUG SQL - select w1_0.wallet_id,w1_0.balance,w1_0.customer_id from wallets w1_0 where w1_0.customer_id=? Customer 3: no wallet
What this code does
findByCustomerIdis a derived query through the link:where w1_0.customer_id=?. The customer itself is never loaded, because the link is lazy.- Customer 3 has no wallet, so the query finds nothing and the
Optionalis empty: a one-to-one is "at most one". - The UNIQUE key
uq_wallets_customeris what stops a second wallet for the same customer.
Without UNIQUE the foreign key would simply be a many-to-one. These teaching tables exist only in the lab database; ShopLite has no wallets.
In Java the side with the column owns the link: Wallet gets @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "customer_id", unique = true) Customer customer. unique = true documents the constraint for Hibernate; MySQL's UNIQUE key is what really enforces it. The other side, Customer.wallet, is optional and uses mappedBy = "customer"; the next sections show why adding it is often a mistake.
@MapsId: sharing the primary key
A shared primary key one-to-one uses the parent's id as the child's id: loyalty_cards.customer_id is both the primary key and the foreign key. In JPA, @MapsId on the @OneToOne copies the id from the linked parent.
The loyalty card of customer 3 has id 3. One column does both jobs.
Example 2 · LoyaltyCard.java: @MapsId shares the customer's id
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
package com.shoplite.lab.customer;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.FetchType;import jakarta.persistence.Id;import jakarta.persistence.JoinColumn;import jakarta.persistence.MapsId;import jakarta.persistence.OneToOne;import jakarta.persistence.Table;
@Entity@Table(name = "loyalty_cards")public class LoyaltyCard {
@Id private Integer id;
@MapsId @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "customer_id") // primary key AND foreign key private Customer customer;
@Column(name = "card_number") private String cardNumber;
private int points;
protected LoyaltyCard() { }
public LoyaltyCard(Customer customer, String cardNumber) { this.customer = customer; this.cardNumber = cardNumber; }
public Integer getId() { return id; } public String getCardNumber() { return cardNumber; } public int getPoints() { return points; }}
// CustomerLabService: issueCard(3, "SL-0000-0003") then cardOf(3)@Transactionalpublic void issueCard(int customerId, String number) { Customer customer = customers.getReferenceById(customerId); LoyaltyCard card = cards.save(new LoyaltyCard(customer, number)); System.out.println("Card " + card.getCardNumber() + " has id " + card.getId());}
@Transactional(readOnly = true)public void cardOf(int customerId) { cards.findById(customerId) // the customer's id IS the card's id .ifPresent(c -> System.out.println("Card " + c.getCardNumber() + ", points " + c.getPoints()));}Card SL-0000-0003 has id 3 DEBUG SQL - insert into loyalty_cards (card_number,points,customer_id) values (?,?,?) DEBUG SQL - select lc1_0.customer_id,lc1_0.card_number,lc1_0.points from loyalty_cards lc1_0 where lc1_0.customer_id=? Card SL-0000-0003, points 0
What this code does
- The card has id 3 right after
save, before any SQL:@MapsIdcopied it from the customer proxy.getReferenceByIdgave that proxy without a SELECT. - The INSERT comes at commit, not at
save: only IDENTITY ids force an immediate insert, and this id is not generated. The Persistence Context module explains this timing. - Reading the card is
findById(customerId)onloyalty_cardsalone;Customerneeds no field for it.
Uniqueness comes for free and there is no extra index. In JPA the child has an @Id Integer id without @GeneratedValue, and @MapsId tells Hibernate to copy the id from the linked customer. The child cannot exist without its parent, which is exactly the meaning of a loyalty card.
The big win is reading: the card of customer 3 is just cards.findById(3). You need no link from Customer to LoyaltyCard at all, which also avoids the problem in the next section.
The inverse side of @OneToOne is never really lazy
The inverse side of a @OneToOne is the field with mappedBy, such as Customer.wallet. Its table has no column for the link, so Hibernate cannot know whether a wallet exists without querying, and fetch = LAZY there is quietly ignored.
Load all customers and never touch getWallet(). With the inverse side mapped, count the queries.
Example 3 · Customer.wallet as the inverse side: 1 + 8 queries
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
package com.shoplite.lab.customer;
import java.time.LocalDateTime;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.FetchType;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.OneToOne;import jakarta.persistence.Table;
@Entity@Table(name = "customers")public class Customer {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "customer_id") private Integer id;
@Column(name = "full_name") private String fullName;
private String email; private String phone;
@Column(name = "created_at", insertable = false, updatable = false) private LocalDateTime createdAt;
@OneToOne(mappedBy = "customer", fetch = FetchType.LAZY) private Wallet wallet;
protected Customer() { }
public Integer getId() { return id; } public String getFullName() { return fullName; } public Wallet getWallet() { return wallet; }}
// CustomerLabService.listCustomers@Transactional(readOnly = true)public void listCustomers() { List<Customer> all = customers.findAll(); // we never call getWallet() System.out.println("Loaded " + all.size() + " customers");}
// Run 2: the same code with the wallet field (and getWallet) removed from Customer--- Run 1: with @OneToOne(mappedBy = "customer", fetch = FetchType.LAZY) DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 DEBUG SQL - select w1_0.wallet_id,w1_0.balance,w1_0.customer_id from wallets w1_0 where w1_0.customer_id=? DEBUG SQL - select w1_0.wallet_id,w1_0.balance,w1_0.customer_id from wallets w1_0 where w1_0.customer_id=? DEBUG SQL - select w1_0.wallet_id,w1_0.balance,w1_0.customer_id from wallets w1_0 where w1_0.customer_id=? DEBUG SQL - select w1_0.wallet_id,w1_0.balance,w1_0.customer_id from wallets w1_0 where w1_0.customer_id=? DEBUG SQL - select w1_0.wallet_id,w1_0.balance,w1_0.customer_id from wallets w1_0 where w1_0.customer_id=? DEBUG SQL - select w1_0.wallet_id,w1_0.balance,w1_0.customer_id from wallets w1_0 where w1_0.customer_id=? DEBUG SQL - select w1_0.wallet_id,w1_0.balance,w1_0.customer_id from wallets w1_0 where w1_0.customer_id=? DEBUG SQL - select w1_0.wallet_id,w1_0.balance,w1_0.customer_id from wallets w1_0 where w1_0.customer_id=? Loaded 8 customers --- Run 2: without the inverse side DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 Loaded 8 customers
What this code does
- Run 1 asks LAZY, yet Hibernate sends one wallets query per customer, 8 in all, because the customers row cannot say whether a wallet exists.
- The code never touched
getWallet(). The cost is paid by every query that loads customers, all over the app. - Run 2 drops the inverse field: one SELECT. When a screen needs the wallet,
wallets.findByCustomerId(id)(Example 1) fetches it.
For a lazy link Hibernate puts a proxy in the field. On the owning side the foreign key column says which row the proxy stands for, or that it is NULL. On the inverse side the customers row has no such column, so Hibernate must ask the wallets table for every customer it loads, and customers.findAll() becomes 1 + N queries. (Bytecode enhancement, a build-time Hibernate plugin, can change this, but this course does not use it.)
The fixes, simplest first: do not map the inverse side, and load the wallet with wallets.findByCustomerId(id) when you need it; or use @MapsId and findById(customerId). Map Customer.wallet only if you truly always need the wallet with the customer.
Predict the output
Count the wallet queries
ShopLite has 8 customers. How many SELECTs does each call send?
Round 1 of 3
findAll() with the lazy inverse side mapped.
When a one-to-one should be columns or an @Embeddable
An @Embeddable is a small value class whose fields are stored as extra columns in the owner's table instead of a table of its own. The owner holds it with @Embedded; ShopLite's Address holds a PostalAddress this way.
A second table is not always needed. Some data fits as a few extra columns in the customers row.
@Embeddablepublic record NotificationPrefs( @Column(name = "sms_alerts") boolean smsAlerts, @Column(name = "email_alerts") boolean emailAlerts) {}
// in Customer: two extra columns in the customers row, no join, no extra query@Embeddedprivate NotificationPrefs prefs;Ask first whether the second table should exist at all. If every customer has exactly one of the thing, it is always read with the customer, and it has no life of its own, it belongs in the customers row: a few extra columns grouped in Java as an @Embeddable.
A separate table with @OneToOne pays off when the data is optional for most rows (a wallet only for customers who opened one), large and rarely read (KYC documents, a profile photo), written by a different part of the system, or secured differently. A quick guide: always present and small, use columns and @Embeddable; optional, big or separately owned, use its own table, preferably with @MapsId, and no inverse mapping unless you need it.
Next step
Check your understanding
12 quick questions