equals and hashCode for entities
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A product loaded twice is two Java objects for one row, and a new customer gets its id only after save(). If equals and hashCode ignore either fact, sets and maps lose or duplicate objects without any error.
Why the default Object.equals breaks for entities
Example 1 loads the same product row twice and puts both objects in a wishlist.
Example 1 · The same row, two objects, default equals
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
package com.shoplite.product;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
import java.util.HashSet;import java.util.Set;
@Componentclass ProductDemoRunner implements CommandLineRunner {
private final ProductRepository products;
ProductDemoRunner(ProductRepository products) { this.products = products; }
@Override public void run(String... args) { Product first = products.findById(1).orElseThrow(); // one SELECT Product second = products.findById(1).orElseThrow(); // another SELECT, a new object
System.out.println("Same row, same object (==)? " + (first == second)); System.out.println("Same row, equals? " + first.equals(second));
Set<Product> wishlist = new HashSet<>(); wishlist.add(first); wishlist.add(second); System.out.println("Wishlist size: " + wishlist.size()); }}DEBUG ... org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? DEBUG ... org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? Same row, same object (==)? false Same row, equals? false Wishlist size: 2
What this code does
Producthere has noequalsof its own (the class from the Enums lesson). TwoSELECTstatements built two objects for row 1.- With
Object.equalsthey count as two products, so the wishlist holds the Redmi twice. - Inside one transaction, the second
findByIdwould return the first object again (the Persistence Context module shows this), but code cannot rely on that.
Object.equals, the version every class gets when it does not write its own, is this == other: equal only to the very same object in memory. For entities that is often wrong, because the same row can live in several objects. Each findById outside a transaction uses a new persistence context (Hibernate's per-transaction cache of loaded objects, covered in the Persistence Context module), so two calls give two different Product objects for row 1.
So an entity needs an equals that means "same row". The obvious idea, compare ids, has a trap of its own, shown next.
The HashSet bug: a hashCode that changes after save
A hash bucket is the slot a HashSet or HashMap picks from an object's hashCode() when it is added. If hashCode() changes later, the set looks in a different bucket and cannot find the object.
An IDE-generated hashCode based on the id changes when save() fills in the id. Example 2 loses a customer that way.
Example 2 · An id-based hashCode loses a customer after save
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
// src/main/java/com/shoplite/customer/Customer.java (equals and hashCode)// BROKEN: hashCode changes when save() fills in the id@Overridepublic boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Customer other)) return false; return Objects.equals(id, other.id);}
@Overridepublic int hashCode() { return Objects.hash(id);}
// src/main/java/com/shoplite/customer/CustomerDemoRunner.javapackage com.shoplite.customer;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
import java.util.HashSet;import java.util.Set;
@Componentclass CustomerDemoRunner implements CommandLineRunner {
private final CustomerRepository customers;
CustomerDemoRunner(CustomerRepository customers) { this.customers = customers; }
@Override public void run(String... args) { Customer sneha = new Customer("Sneha Patil", "sneha.patil@example.com", "9876543209"); Customer rahul = new Customer("Rahul Verma", "rahul.verma@example.com", null);
Set<Customer> festWinners = new HashSet<>(); festWinners.add(sneha); festWinners.add(rahul); System.out.println("Before save: size " + festWinners.size() + ", contains sneha? " + festWinners.contains(sneha));
customers.save(sneha); System.out.println("After save: size " + festWinners.size() + ", contains sneha? " + festWinners.contains(sneha)); System.out.println("Removed sneha? " + festWinners.remove(sneha) + ", size now " + festWinners.size());
Customer loaded = customers.findById(sneha.getId()).orElseThrow(); System.out.println("Loaded copy equals sneha? " + loaded.equals(sneha)); }}Before save: size 1, contains sneha? true DEBUG ... org.hibernate.SQL : insert into customers (email,full_name,phone) values (?,?,?) After save: size 1, contains sneha? false Removed sneha? false, size now 1 DEBUG ... org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? Loaded copy equals sneha? true
What this code does
- Before any save, Sneha and Rahul both have
id == null, so thisequalscalls them equal and the set silently drops Rahul: size 1, not 2. - After
save, Sneha's id is 9 and her hash changed. She is still inside the set, butcontainsandremovelook in the new bucket and fail. - Comparing with a freshly loaded copy works, which is why this bug survives simple tests.
A new customer has id == null, and save() fills in 9, so the hash changes and the customer is "lost" inside the set: contains says false and remove does nothing (Example 2).
There is a second bug in the same code: with Objects.equals(id, other.id), two different new customers (both null ids) are equal, so the set kept only one of them. That is real data silently thrown away.
Trace the code
Watch the customer get lost
Variables
- id
- null
Output
(nothing printed yet)Line 14A new customer has no id yet, so id is null.
Two safe designs: a natural key, or the id with a constant hashCode
A natural key is a business value that is unique and never changes, such as an ISBN. If an entity has one, equals and hashCode can compare it.
If an entity has a natural key, compare by it. The snippet compares a Book by its isbn.
// Natural key: only when the value is unique AND can never change@Overridepublic boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Book other)) return false; return isbn.equals(other.getIsbn());}
@Overridepublic int hashCode() { return isbn.hashCode();}Example 3 · The fix: id-based equals with a constant hashCode
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
// src/main/java/com/shoplite/customer/Customer.java (equals and hashCode)// Two customers are equal when both have the same database id.// A new customer (id still null) is equal only to itself.@Overridepublic boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Customer other)) return false; return id != null && id.equals(other.getId());}
@Overridepublic int hashCode() { return Customer.class.hashCode();}Before save: size 2, contains sneha? true DEBUG ... org.hibernate.SQL : insert into customers (email,full_name,phone) values (?,?,?) After save: size 2, contains sneha? true Removed sneha? true, size now 1 DEBUG ... org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? Loaded copy equals sneha? true
What this code does
- Two new customers are different (each is equal only to itself, via
this == o), so both stay in the set. - The hash never changes, so after
savethe set still finds and removes Sneha. A loaded copy with id 9 equals her too. - This is the pattern on every ShopLite entity:
instanceof,id != null, the other side'sgetId(), andCustomer.class.hashCode().
ShopLite has no such field: an admin can change a product's SKU (PUT /products/{id}) and a customer's e-mail. So ShopLite uses the second design, an id-based equals with a constant hashCode: two objects are equal when both have the same non-null id, a new object is equal only to itself, and hashCode() returns the same number for every customer, so it can never change (Example 3).
A constant hash puts all customers in one bucket, so a HashSet of thousands of entities gets slower. Entity sets are usually small (the items of one order), so this is the accepted trade-off for correctness.
Hibernate proxies: instanceof, not getClass(), and why not Lombok @Data
A proxy is a subclass Hibernate generates at runtime, such as Product$HibernateProxy, that stands in for an entity that is not loaded yet. Its own fields stay empty; only its methods reach the real data.
getReferenceById(1) returns a proxy without a SELECT. Example 4 compares it with a loaded product.
Example 4 · A proxy: getClass() vs instanceof, and toString after the transaction
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
// src/main/java/com/shoplite/product/Product.java (the end of the class)// IDE-generated style: compares classes with getClass()public boolean equalsByClass(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Product other = (Product) o; return id != null && id.equals(other.id);}
// Safe style: instanceof and the getter (a proxy's own fields are empty)@Overridepublic boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Product other)) return false; return id != null && id.equals(other.getId());}
@Overridepublic int hashCode() { return Product.class.hashCode();}
@Overridepublic String toString() { return "Product[id=" + getId() + ", sku=" + getSku() + "]";}
package com.shoplite.product;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;import org.springframework.transaction.support.TransactionTemplate;
@Componentclass ProductDemoRunner implements CommandLineRunner {
private final ProductRepository products; private final TransactionTemplate tx;
ProductDemoRunner(ProductRepository products, TransactionTemplate tx) { this.products = products; this.tx = tx; }
@Override public void run(String... args) { tx.executeWithoutResult(status -> { Product proxy = products.getReferenceById(1); System.out.println("Class: " + proxy.getClass().getSimpleName()); Product real = products.findById(1).orElseThrow(); System.out.println("Same object? " + (proxy == real)); });
Product loaded = products.findById(1).orElseThrow(); Product proxyOutside = tx.execute(status -> { Product p = products.getReferenceById(1); p.getSku(); return p; }); System.out.println("equalsByClass: " + loaded.equalsByClass(proxyOutside)); System.out.println("equals: " + loaded.equals(proxyOutside));
Product neverLoaded = tx.execute(status -> products.getReferenceById(2)); try { System.out.println(neverLoaded); } catch (RuntimeException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); } }}Class: Product$HibernateProxy DEBUG ... org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? Same object? true DEBUG ... org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? DEBUG ... org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? equalsByClass: false equals: true LazyInitializationException: Could not initialize proxy [com.shoplite.product.Product#2] - no session
What this code does
TransactionTemplateruns a lambda inside one transaction (the Transactions module explains it). Inside it,getReferenceById(1)gave aProduct$HibernateProxywith noSELECT;findById(1)then loaded the row into that same proxy.equalsByClasscomparesProductwithProduct$HibernateProxyand says "different" for the same row. Theinstanceofversion withother.getId()says "equal".- The last proxy was never loaded, and its transaction has ended. Calling
toString()on it has to load the row first, so it throws. Never log a proxy you have not loaded; log ids or DTOs.
Lazy relationships (Relationships module) return proxies all the time, so equals follows two rules: test the type with instanceof, because getClass() of a proxy is Product$HibernateProxy, not Product; and read the other side through getters (other.getId()), never other.id. Example 4 shows a getClass()-based equals calling a loaded product and a proxy of the same row "different".
Lombok is a library that generates code from annotations. Its @Data on an entity generates equals/hashCode from every field (they change when any field changes, and touch lazy data) and a toString of every field (which loads lazy data, and loops forever on two-way links). ShopLite writes these methods by hand.
toString without lazy data
A toString on an entity should print only the id and a few simple columns: never relationships, collections or large text.
@Overridepublic String toString() { // id and simple columns only: no relationships, no collections return "Product[id=" + id + ", sku=" + sku + "]";}A toString is called by loggers, debuggers and string concatenation, often after the transaction has ended. On a loaded entity, printing a lazy relationship loads it, or fails outside a transaction. On an unloaded proxy, calling any method except getId(), toString() included, loads the row first; after the transaction that fails with LazyInitializationException: Could not initialize proxy [com.shoplite.product.Product#2] - no session (the last line of Example 4). A log line should never be able to crash a request.
Every ShopLite entity has a short toString such as Product[id=1, sku=MOB-RN13], built from its own fields. When relationships arrive in the Relationships module, they stay out of toString.
Next step
Check your understanding
11 quick questions