๐Ÿ”ด The Error You're Seeing

Confirm this matches your console output. If it does, you're in the right place.

ERROR LOG2026-02-18 12:30:45.001 ERROR 8842 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: jakarta.persistence.EntityNotFoundException: Unable to find com.devinhyderabad.entity.User with id 1] with root cause jakarta.persistence.EntityNotFoundException: Unable to find com.devinhyderabad.entity.User with id 1

โšก Quick Fix Works 80% of the time

Use `findById(id)` which returns `Optional<T>` instead of `getOne(id)` or `getReference(id)`.

User user = repo.findById(1L) .orElseThrow(() -> new ResourceNotFoundException("User not found"));

๐Ÿง  Why this Happens

Tap to expand the deep technical explanation

You used a method like `getReferenceById()` or `getOne()` to fetch an entity. These methods return a lazy-loading proxy. The actual database query is delayed until you access a property. When you finally access it, Hibernate queries the DB, finds no matching record, and throws `EntityNotFoundException`.

The HITEC City Parking Spot Analogy:

It's like ordering a specific book from a library catalog. The librarian gives you a placeholder (Proxy). When you try to open the book to read it, the librarian goes to the shelf, realizes the book is missing, and throws an error instead of giving you the book.

๐Ÿ” How to Reproduce Confirm this is your error

Call `repo.getReferenceById(999L)` where ID 999 does not exist in the database. Try to call `user.getName()` on the returned object. The exception will throw at that exact moment.

๐Ÿ› ๏ธ Solutions (5 Ways to Fix)

Solution 1โœ“ Most common cause

Use findById() instead of getReferenceById()

๐Ÿ‘‰ Use this as the default way to fetch entities by ID.

`findById()` hits the database immediately and returns an `Optional`. If the record isn't there, the Optional is empty, avoiding the proxy crash.

User user = repo.findById(1L) .orElseThrow(() -> new RuntimeException("User not found"));
Solution 2

Check if the record exists before accessing

๐Ÿ‘‰ Use this if you must use a proxy (e.g., for setting a foreign key relationship).

If you only need the proxy to satisfy a foreign key, check `existsById()` before calling `getReferenceById()`.

if (repo.existsById(1L)) { User proxy = repo.getReferenceById(1L); order.setUser(proxy); // Safe, we know it exists } else { throw new RuntimeException("User not found"); }
Solution 3

Verify database data integrity

๐Ÿ‘‰ Use this if the record should exist but Hibernate says it doesn't.

Manually query the database to ensure the row hasn't been deleted by another process.

SELECT * FROM users WHERE id = 1;
Solution 4

Handle the exception globally

๐Ÿ‘‰ Use this to return a clean 404 JSON response instead of a 500 error.

Create a global exception handler to catch EntityNotFoundException.

@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(EntityNotFoundException.class) public ResponseEntity<String> handleNotFound(EntityNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage()); } }
Solution 5

Check transaction boundaries

๐Ÿ‘‰ Use this if the entity was found initially but disappears later in the same request.

If a method deletes the entity in the same transaction before you access it via proxy, Hibernate will fail to find it.

@Transactional public void doWork(Long id) { User user = repo.getReferenceById(id); repo.delete(user); // Deleted user.getName(); // Throws EntityNotFoundException! }

๐Ÿ“‹ Version Notes

Spring Boot 2.x

Uses `getOne()` which returns a proxy. Throws javax.persistence.EntityNotFoundException.

Spring Boot 3.x

`getOne()` is deprecated. Uses `getReferenceById()`. Throws jakarta.persistence.EntityNotFoundException.

๐Ÿ›ก๏ธ How to Prevent This Next Time

Always prefer `findById()` for reading data. Reserve `getReferenceById()` strictly for setting foreign key relationships where you don't need to read the parent object's fields.

Course Search
Search across all chapters & stages
๐Ÿ“–

Search the course

Type any topic โ€” branching, stash, rebase, hooks โ€” and jump straight to that chapter.

merge branchesgit stashundo commitrebase