The Wild

Retrieve Object from Database in Hibernate

· 5 min read · Mammals

In this article
  1. Background: What Hibernate Does Under the Hood
  2. How to Retrieve an Object by Primary Key
  3. Retrieving with HQL (Hibernate Query Language)
  4. Using Criteria API and Native SQL
  5. How to Choose the Right Retrieval Method
  6. Common Problems and How to Avoid Them
  7. Performance Considerations and Caching
  8. Frequently Asked Questions

To retrieve an object from a database in Hibernate, you use the Session.get() or Session.load() method with the entity class and primary key, or you write a query using HQL, Criteria, or native SQL. The simplest example is session.get(Product.class, 1L), which returns the Product with id 1 or null if not found.

Background: What Hibernate Does Under the Hood

Hibernate is an Object-Relational Mapping (ORM) framework for Java. It maps Java classes to database tables and Java data types to SQL data types. When you retrieve an object, Hibernate translates your Java-level call into SQL, executes it, and then constructs a fully populated Java object from the result set. It also manages a first-level cache (the session) and optionally a second-level cache to reduce database round trips.

Hibernate supports several retrieval strategies, each with different semantics around lazy loading, caching, and exception behavior. Understanding these differences helps you choose the right method for your use case.

How to Retrieve an Object by Primary Key

The most direct way is to use the session's get() or load() methods. Both take the entity class and the primary key value. Here is a typical example:

  1. Open a session from the session factory: Session session = sessionFactory.openSession();
  2. Call get() or load(): Product product = session.get(Product.class, 1L);
  3. Use the object, then close the session: session.close();

The key difference between get() and load():

  • get() hits the database immediately (unless already in cache) and returns null if the row does not exist.
  • load() returns a proxy without hitting the database until you access a property (lazy loading). If the row does not exist, it throws an ObjectNotFoundException when you access the proxy.

In practice, use get() when you are not sure the object exists, and load() when you are certain and want to avoid an extra query (for example, when setting a reference for a new entity).

Retrieving with HQL (Hibernate Query Language)

HQL is similar to SQL but operates on entity objects and their properties, not table columns. To retrieve all products:

Query<Product> query = session.createQuery("from Product", Product.class);
List<Product> products = query.list();

To retrieve a single object with a condition:

Query<Product> query = session.createQuery("from Product where id = :id", Product.class);
query.setParameter("id", 1L);
Product product = query.uniqueResult();

HQL supports joins, projections, aggregation, and ordering. It is the recommended choice for most read operations because it is database-independent and type-safe when using JPA's TypedQuery.

Using Criteria API and Native SQL

The Criteria API (now CriteriaBuilder in JPA 2.0+) provides a programmatic, type-safe way to build queries without string syntax. Example:

CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Product> cr = cb.createQuery(Product.class);
Root<Product> root = cr.from(Product.class);
cr.select(root).where(cb.equal(root.get("id"), 1L));
Product product = session.createQuery(cr).getSingleResult();

For complex, database-specific queries, you can use native SQL:

NativeQuery<Product> query = session.createNativeQuery("SELECT * FROM product WHERE id = ?", Product.class);
query.setParameter(1, 1L);
Product product = query.getSingleResult();

Native SQL gives you full control but ties your code to a specific database dialect. Use it only when HQL or Criteria cannot express the query efficiently.

How to Choose the Right Retrieval Method

Your choice depends on the situation:

  • If you have the primary key and need the object immediately, use get().
  • If you have the primary key and want lazy loading (e.g., to set a reference without loading the whole object), use load().
  • If you need to filter, join, or aggregate, use HQL or Criteria.
  • If you need a database-specific feature (e.g., window functions), use native SQL.
  • If you are using JPA (Java Persistence API) in a Spring or Java EE environment, you typically use EntityManager.find() (similar to get()) or getReference() (similar to load()).

Also consider the fetch strategy. By default, @ManyToOne associations are eager, while @OneToMany are lazy. You can override with @ManyToOne(fetch = FetchType.LAZY) or use JOIN FETCH in HQL to eagerly load associations in a single query.

Common Problems and How to Avoid Them

Several pitfalls are common when retrieving objects:

  • LazyInitializationException: Occurs when you access a lazy association after the session is closed. Solution: initialize the association inside the session (e.g., with Hibernate.initialize()) or use a fetch join.
  • ObjectNotFoundException: Thrown by load() when the row does not exist. Use get() if you are unsure.
  • MultipleBagFetchException: When fetching two or more collections with JOIN FETCH in the same query. Solution: fetch one collection or use Set instead of List.
  • N+1 query problem: When you retrieve a list of entities and then access each one's lazy association, Hibernate executes one query per entity. Solution: use JOIN FETCH or a batch fetching strategy.

To debug, enable Hibernate's SQL logging by setting hibernate.show_sql=true in your configuration.

Performance Considerations and Caching

Retrieval performance depends on the number of queries and the amount of data fetched. Hibernate's first-level cache is always on and caches objects within a session. The second-level cache (if configured) stores objects across sessions. For read-heavy applications, enable second-level caching for entities that change rarely.

When retrieving lists, use pagination with setFirstResult() and setMaxResults() to avoid loading thousands of rows. Also, select only the columns you need using a projection (e.g., select p.name from Product p) to reduce memory usage.

Frequently Asked Questions

What is the difference between get() and load() in Hibernate?

get() immediately queries the database and returns null if the row is missing. load() returns a proxy without hitting the database until you access a property, and throws an exception if the row does not exist. Use get() for safety, load() for performance when you are certain the object exists.

How do I retrieve all rows from a table in Hibernate?

Use HQL: session.createQuery("from Product", Product.class).list(). This returns a List<Product> containing all rows. Be cautious with large tables; consider pagination or criteria restrictions.

Can I retrieve an object without knowing its primary key?

Yes, use a query with a condition on any property. For example, session.createQuery("from Product where name = :name", Product.class).setParameter("name", "Laptop").uniqueResult(). This returns the first matching object or null.

Why do I get LazyInitializationException when accessing a collection?

This happens when you try to access a lazy-loaded collection after the Hibernate session is closed. To fix, initialize the collection while the session is open (e.g., call Hibernate.initialize(product.getOrders())) or use a fetch join in the query.

Is it better to use HQL or Criteria API?

Both are valid. HQL is more readable for complex queries, while Criteria is type-safe and refactor-friendly because it uses Java methods instead of strings. For dynamic queries (where conditions change at runtime), Criteria is often easier to build programmatically.