Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What is the difference between entityManager.find(Order.class, id) and entityManager.getReference(Order.class, id)? When would you use getReference?

find() gives us the real entity, or null when no row exists, and it usually runs a SELECT unless the entity is already in the persistence context. getReference() may give us an uninitialized proxy without touching the database at all; the SELECT runs only when we read a field, and if the row is missing we get an EntityNotFoundException at that later moment. We use getReference() when we only need the entity as a foreign key, for example line.setOrder(em.getReference(Order.class, orderId)).

Why this question is asked

Loading an entity looks like the simplest thing JPA does, yet these two methods behave very differently, and choosing the wrong one costs either an extra query on every request or a confusing exception far away from the line that caused it. Interviewers ask this to see whether we understand the persistence context and Hibernate proxies, which sit behind lazy loading too. In this answer, we will recap what the persistence context is, look at what each method does step by step, see where getReference() fails, and then use it for the job it is made for: setting a foreign key without loading the parent.

1A Quick Recap of the Persistence Context

The EntityManager keeps a persistence context, a per-transaction map from (entity class, id) to the managed entity object. Whenever we load an entity, Hibernate first looks in this map. If the entity is there, we get the same Java object back, and no SQL runs. This is often called the first-level cache.

A proxy is a different idea. It is an object of a subclass that Hibernate generates at runtime, which looks like an Order from the outside but holds only the id. The first time we call a getter for a non-id field, the proxy runs the SELECT, fills itself, and from then on behaves like the real entity. Lazy many-to-one associations use exactly the same proxies.

2What find() Does

find() asks for the real object now. Hibernate checks the persistence context first; if the entity is not there, it runs a SELECT by primary key, builds the entity, stores it in the context and returns it. If no row matches, it returns null, so the caller decides what absence means.

Java
Order a = em.find(Order.class, 42L); // select ... from orders where id=42
Order b = em.find(Order.class, 42L); // no SQL: same object from the persistence context
System.out.println(a == b); // true
Order c = em.find(Order.class, 999L); // select ... where id=999
System.out.println(c); // null: no such row

Notice that the second call is free. So calling find() twice for the same id in one transaction is cheap; the first call is the one that pays.

3What getReference() Does

getReference() asks only for something that stands for the entity. If the entity is already in the persistence context, Hibernate returns it. If not, Hibernate returns a proxy holding the id and runs no SQL. The database is touched only when we read a field other than the id.

Java
Order ref = em.getReference(Order.class, 42L); // no SQL yet
System.out.println(ref.getId()); // 42, still no SQL: the proxy knows its id
System.out.println(ref.getStatus()); // select ... where id=42, then NEW
Order missing = em.getReference(Order.class, 999L); // no SQL, no error yet
missing.getStatus(); // select ... where id=999 -> jakarta.persistence.EntityNotFoundException
find() and getReference() side by side
Questionfind()getReference()
Returnsthe real entity or nullthe entity if loaded, otherwise a proxy
SQL at the calla SELECT unless already in the contextnone
Missing rownull at onceEntityNotFoundException on first field access
Good forreading the entitysetting a foreign key or a relationship

But there is a catch: the error does not come from the getReference() line. It comes from whichever line first touches the proxy, which may be in a mapper or a JSON serializer far away. And if the transaction has already ended when the proxy is first touched, we get a LazyInitializationException instead, because there is no session left to run the SELECT.

4Using getReference() to Set a Foreign Key

The best use is when we only need the parent so that Hibernate can write its id into a foreign key column. Suppose we add a line to an existing order. With find(), we would load the whole order just to throw its data away.

Java
@Transactional
public void addLine(long orderId, String sku, int qty) {
OrderLine line = new OrderLine(sku, qty);
line.setOrder(em.getReference(Order.class, orderId)); // no select on orders
em.persist(line);
}
// SQL at flush: insert into order_line (order_id, sku, qty, id) values (42, 'A-1', 2, 1001)

Only one statement runs. If the order does not exist, the foreign key constraint in the database rejects the insert, so we still do not store a broken row. The difference is that the failure is a constraint violation at flush rather than a clean null we could check, which is fine when the id came from a trusted place and less fine when it came straight from user input.

5The Same Choice in Spring Data JPA

Spring Data exposes both. findById() calls find() and wraps the result in an Optional. getReferenceById() calls getReference(); it replaced the older getOne(), which is deprecated. So orderRepository.getReferenceById(orderId) is the Spring Data way to write the foreign key example above.

Java
line.setOrder(orderRepository.getReferenceById(orderId)); // proxy, no select
Order o = orderRepository.findById(orderId).orElseThrow(); // select now, fails here if missing

6Follow-up questions

Does getReference() always avoid the database?

No. It avoids the database at the call, but if any code later reads a non-id field, the proxy runs the SELECT. If the entity is already in the persistence context, getReference() simply returns it. The method is a promise that no SQL is needed yet, not a promise that none will ever run.

Why can a proxy break an equals() method that uses getClass()?

The proxy is an instance of a generated subclass of Order, so proxy.getClass() is not Order.class. An equals() that compares getClass() values says a proxy and a loaded Order with the same id are different. Entity equals() methods should use instanceof or Hibernate.getClass(), and read the id through its getter.

Which one should a REST endpoint that returns the order use?

find(), or findById() in Spring Data. The endpoint needs the data and must answer 404 when the order is missing, and an Optional or a null makes that check clear at the right place.

7Conclusion

In this answer, we saw that find() returns the real entity or null and runs a SELECT unless the entity is already managed, while getReference() can return a proxy without any SQL and fails with EntityNotFoundException only when a field is first read. That makes getReference(), or getReferenceById() in Spring Data, the right tool for setting a foreign key without loading the parent, and find() the right tool whenever we actually need the data.

What to say in the interviewAbout 90 seconds aloud

Open with

find returns the actual entity or null. It checks the persistence context first and otherwise runs a select by primary key, so I know right away whether the row exists. getReference can return an uninitialized Hibernate proxy that only holds the id, with no SQL at all.

Then, if they want more

The select happens the first time I read a non-id field, and if the row is missing I get an EntityNotFoundException at that point, which can be far from the call, or a LazyInitializationException if the transaction is already over.

So I use find when I need the data or need to handle a missing row, for example in a GET endpoint that should return 404. I use getReference when I only need the entity as a foreign key. The classic case is adding a line to an existing order: line.setOrder(em.getReference(Order.class, orderId)) and then persist the line.

Hibernate writes only the insert for the line with the order id, and the foreign key constraint still protects us if the order does not exist. In Spring Data the same pair is findById, which returns an Optional, and getReferenceById, which replaced the deprecated getOne.

One thing I watch with proxies is equals: comparing getClass breaks with proxies, so entity equals methods should use instanceof and the id getter.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is the difference between entityManager.find(Order.class, id) and...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/541bd397d5/