findById() and getOne() (now referenceById() in newer Spring Data versions) both retrieve an entity by its primary key, but they differ in when the database is actually hit -- findById() fetches eagerly and returns an Optional, while getOne() returns a lazy proxy that only queries the database when its fields are first accessed.
Key Points: • findById() returns an Optional<T>, immediately querying the database and returning empty if no match is found. • getOne() returns a proxy object without hitting the database yet, deferring the actual SELECT until a field on the entity is accessed. • If the entity referenced by getOne() doesn't actually exist, the EntityNotFoundException is thrown lazily, at the point the proxy is accessed, not when getOne() is called. • getOne() is useful when you only need the entity's reference (its ID) to set up a relationship, avoiding an unnecessary SELECT. • getOne() is deprecated in newer Spring Data JPA in favor of getReferenceById(), which behaves the same way but with clearer naming.
Example: Setting a foreign key relationship, like assigning an order to a customer, only needs the customer's reference, so getOne(customerId) (or getReferenceById()) avoids a wasted SELECT, whereas displaying the customer's actual details requires findById() to eagerly load the real data.
Code Example:
// Eager fetch, safe existence check via Optional
Optional<Customer> customer = customerRepository.findById(id);
// Lazy proxy, defers the query until fields are accessed
Customer customerRef = customerRepository.getReferenceById(id);
order.setCustomer(customerRef);
orderRepository.save(order);Interview Tip: A concise interview answer is:
"findById() eagerly queries the database and returns an Optional, so I can safely check whether the entity exists. getOne(), now getReferenceById(), returns a lazy proxy that defers the actual query until a field is touched, and throws EntityNotFoundException at that point if the row doesn't exist -- I use it when I just need a reference to set up a relationship without an unnecessary SELECT."