Performance Optimization
-
Performance optimization in Hibernate involves strategies to minimize database interactions, reduce memory consumption, and improve query efficiency.
-
Key techniques include proper fetch strategies, batch processing, pagination, and connection pooling.
Fetch Strategies
Section titled “Fetch Strategies”// Eager vs Lazy Loading@OneToMany(fetch = FetchType.LAZY) // Default for collections@ManyToOne(fetch = FetchType.EAGER) // Default for single-valued associations
// Batch Fetching@Entity@BatchSize(size = 10)public class Department { @OneToMany(mappedBy = "department") private List<Employee> employees;}
// Fetch JoinsString hql = "SELECT d FROM Department d JOIN FETCH d.employees WHERE d.id = :id";Pagination
Section titled “Pagination”Query<User> query = session.createQuery("FROM User ORDER BY username", User.class);query.setFirstResult(0); // start indexquery.setMaxResults(10); // page sizeList<User> users = query.getResultList();