Java Hibernate Fetch Entity List: How-To
In this article
- Background: Why Fetching Lists Is Core to Hibernate
- How It Works: The Main Fetching Methods
- How to Choose the Right Fetch Method
- Common Problems and Misconceptions
- Performance Considerations and Best Practices
- Comparison: Hibernate vs JPA vs Spring Data JPA
- Alternatives to Fetching a Full List
- Frequently Asked Questions
To fetch a list of entities with Java Hibernate, use a HQL/JPQL query like session.createQuery("from Entity", Entity.class).list(), or the Criteria API: session.createCriteria(Entity.class).list(). This returns all rows from the mapped table as a List<Entity>.
Background: Why Fetching Lists Is Core to Hibernate
Hibernate is an Object-Relational Mapping (ORM) framework for Java. It maps database tables to Java classes, so you work with objects instead of SQL result sets. Fetching a list is one of the most common operations—you often need all customers, all orders, or a filtered subset. Hibernate provides several ways to retrieve lists, each with different trade-offs in terms of performance, flexibility, and code readability.
The simplest approach is HQL (Hibernate Query Language), which resembles SQL but works on entity names and properties. Alternatively, the Criteria API offers a type-safe, programmatic way to build queries. Both return a List of entity objects. Under the hood, Hibernate translates these into SQL, executes it, and maps the result rows to entity instances.
How It Works: The Main Fetching Methods
Here are the primary ways to fetch an entity list in Hibernate (using the classic Session API):
- HQL/JPQL:
List<Entity> list = session.createQuery("from Entity", Entity.class).list();— This fetches all entities of the given type. - Criteria API (legacy):
List<Entity> list = session.createCriteria(Entity.class).list();— Works, but deprecated in Hibernate 5 and removed in Hibernate 6. - Criteria API (JPA standard):
CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Entity> cq = cb.createQuery(Entity.class); cq.from(Entity.class); List<Entity> list = session.createQuery(cq).getResultList();— Type-safe and portable. - Native SQL:
List<Entity> list = session.createNativeQuery("SELECT * FROM entity", Entity.class).list();— Use only when you need database-specific SQL.
All these return a List that you can iterate over. The list is typically a java.util.ArrayList or a Hibernate-specific list, but you don’t need to worry about the concrete type.
How to Choose the Right Fetch Method
Your choice depends on your needs:
- Simplicity: HQL with
from Entityis the easiest to read and write. - Dynamic queries: If you need to build conditions at runtime, use the JPA Criteria API—it’s type-safe and avoids string concatenation.
- Performance: If you only need certain columns, use a projection (e.g.,
select e.name from Entity e) to avoid loading whole entities. - Database-specific features: Use native SQL, but be aware you lose portability.
For most applications, HQL is sufficient. For complex, dynamic searches, the Criteria API is better. Avoid native SQL unless you have a clear reason.
Common Problems and Misconceptions
One frequent mistake is assuming that fetching a list automatically fetches all associated entities (like a List<Order> inside a Customer). By default, Hibernate uses lazy loading for collections: the associated list is not loaded until you access it, which can cause a LazyInitializationException if the session is closed. To avoid this, you can:
- Use
JOIN FETCHin HQL:from Customer c join fetch c.orders— this fetches the orders in the same query. - Set
fetch = FetchType.EAGERon the mapping, but that can hurt performance. - Initialize the collection while the session is open, e.g.,
Hibernate.initialize(customer.getOrders()).
Another misconception is that list() and getResultList() are different. In Hibernate 5 and later, they are equivalent; list() is Hibernate-specific, getResultList() is JPA standard. Both return the same result.
Performance Considerations and Best Practices
Fetching a huge list can cause memory issues. Here are practical tips:
- Use pagination:
session.createQuery("from Entity", Entity.class).setFirstResult(0).setMaxResults(100).list();— This limits the result set. - Use projections: If you only need a few fields, select them instead of the whole entity.
- Be mindful of N+1 queries: When you iterate over a list and access a lazy association for each item, Hibernate issues one query per item. Use
JOIN FETCHor batch fetching (@BatchSize) to reduce queries. - Consider read-only queries:
session.setDefaultReadOnly(true)orsetReadOnly(true)on the query can improve performance if you don’t plan to modify the entities.
Always measure performance with realistic data volumes. What works for 100 rows may not work for 100,000.
Comparison: Hibernate vs JPA vs Spring Data JPA
Hibernate is an implementation of the JPA (Java Persistence API) specification. When you use JPA’s EntityManager, you are still using Hibernate underneath if Hibernate is your provider. Spring Data JPA adds a repository layer that simplifies fetching:
- Hibernate Session:
session.createQuery(...)— direct, but tied to Hibernate. - JPA EntityManager:
entityManager.createQuery(...)— portable across JPA providers. - Spring Data JPA:
repository.findAll()orrepository.findByLastName(String)— auto-generated queries, no need to write HQL.
Spring Data JPA is built on JPA and Hibernate, so it’s a higher-level abstraction. For simple list fetching, findAll() is the easiest. For custom queries, you can use @Query annotations or the Criteria API.
Alternatives to Fetching a Full List
Sometimes you don’t need the whole list. Consider these alternatives:
- Scrollable results: Use
session.createQuery(...).scroll(ScrollMode.FORWARD_ONLY)to iterate over a large result set without loading it all into memory. - Streaming: Hibernate 5.2+ supports
session.createQuery(...).stream()which returns a Java 8Streamthat can be processed lazily. - Count query: If you only need the number of entities, use
select count(e) from Entity e. - DTO projection: Fetch only the needed fields into a custom class, e.g.,
select new com.example.MyDto(e.id, e.name) from Entity e.
These approaches reduce memory footprint and improve performance for large datasets.
Frequently Asked Questions
How do I fetch a list with a WHERE clause?
Use HQL: from Entity e where e.status = :status and set the parameter via setParameter("status", value). Or use Criteria API: cq.where(cb.equal(root.get("status"), value)).
Why do I get a LazyInitializationException when accessing a list?
This happens when you try to access a lazy-loaded collection after the Hibernate session is closed. Solutions: fetch the collection eagerly in the query using JOIN FETCH, or initialize it before closing the session, or use a transaction that stays open during view rendering (though not recommended).
Can I fetch a list of only specific columns?
Yes, use a projection: select e.id, e.name from Entity e. This returns a List<Object[]> unless you use a DTO constructor expression. It’s more efficient than fetching full entities.
What is the difference between list() and getResultList()?
In Hibernate 5 and later, they are functionally identical. list() is Hibernate’s original method, getResultList() is the JPA standard method. Both return the same List.
How do I fetch a list with pagination?
Use setFirstResult(int) and setMaxResults(int) on the query. For example, session.createQuery("from Entity", Entity.class).setFirstResult(0).setMaxResults(20).list() returns the first 20 rows.
Is it safe to fetch all rows of a large table?
It can cause memory issues and slow performance. Always consider pagination, streaming, or projections. If you must fetch all, ensure your heap size is sufficient and consider using scroll() for read-only iteration.