Junior — Middle
How can the lazy loading mechanism in Hibernate be forcibly disabled?
sobes.tech AI
Answer from AI
Hibernate's lazy loading mechanism by default loads related entities only when they are first accessed, which saves resources. To explicitly disable lazy loading and enable eager loading, you can:
- Use the
@OneToMany(fetch = FetchType.EAGER)annotation or a similar one withFetchType.EAGERfor the desired field. - In HQL or Criteria queries, use
join fetchto explicitly join related entities. - Configure globally through settings, but this is not recommended as it can lead to excessive data loading.
Example:
@Entity
public class Author {
@OneToMany(fetch = FetchType.EAGER)
private Set<Book> books;
}
Or in a query:
String hql = "FROM Author a JOIN FETCH a.books WHERE a.id = :id";