Junior — Middle
What methods or approaches do you use to load data into Hibernate to manage their retrieval and efficiency?
sobes.tech AI
Answer from AI
Methods and approaches commonly used to manage data loading in Hibernate and improve retrieval efficiency include:
- Eager fetching — related entities are loaded immediately along with the main entity.
- Lazy fetching — related entities are loaded only upon first access, avoiding unnecessary queries.
- JPQL/HQL queries with JOIN FETCH — explicitly specify which related objects to load along with the main entity.
- Entity Graphs — a declarative way to specify which associations to load.
- Batch fetching — loading related entities in batches to reduce the number of queries.
Example of using lazy loading and JOIN FETCH:
// In the entity
@OneToMany(fetch = FetchType.LAZY)
private Set<Order> orders;
// In the query
String hql = "FROM Customer c JOIN FETCH c.orders WHERE c.id = :id";
Customer customer = session.createQuery(hql, Customer.class)
.setParameter("id", customerId)
.uniqueResult();