A timeout increase hides the problem; instead, measure, read the plan and fix the cause. 1. See the actual SQL - Enable logging in development: logging.level.org.hibernate.SQL=DEBUG and logging.level.org.hibernate.orm.jdbc.bind=TRACE for parameters, or use datasource-proxy or p6spy for SQL with timings. - Hibernate statistics (hibernate.generate_statistics=true) show query counts, entity loads and slow queries (hibernate.log_slow_query threshold in Hibernate 6). - In production, use APM traces or database tools (pg_stat_statements in PostgreSQL, Performance Schema in MySQL, Query Store in SQL Server). 2. Check whether it is really one slow query - Many requests are slow because of N+1 queries — hundreds of small statements. Fix with JOIN FETCH, entity graphs, batch fetching or DTO projections. 3. Analyse the execution plan - Run EXPLAIN ANALYZE (PostgreSQL) or EXPLAIN (MySQL) with realistic parameters and data volume. - Look for sequential scans on large tables, wrong join orders, sorts spilling to disk, bad row estimates and functions applied to indexed columns. 4. Typical fixes - Add or adjust indexes matching WHERE, JOIN and ORDER BY columns; covering indexes for frequent queries. - Rewrite non-sargable conditions: lower(name) = ? needs a functional index, LIKE '%x%' needs full-text or trigram indexes, and mismatched parameter types can cause implicit conversions. - Select fewer columns with projections instead of loading full entities with large text or binary columns. - Avoid fetch-joining collections with pagination (Hibernate then paginates in memory); paginate IDs first, then fetch details. - Use keyset pagination for deep pages. - Replace row-by-row processing with set-based JPQL or SQL updates (@Modifying queries) for bulk changes. - Use read-only transactions or hints (org.hibernate.readOnly) for large read queries to reduce dirty-checking overhead. - For complex reporting, a native query, database view or materialized view may be clearer and faster. 5. Check the database environment - Outdated statistics (ANALYZE), table bloat, lock contention from long transactions and connection-pool waits can make good queries slow. 6. Verify and protect - Re-measure with production-like data, add a performance or query-count test for the scenario, and monitor query duration. Keep reasonable timeouts (spring.jpa.properties.jakarta.persistence.query.timeout) as protection — but as a safety net, not a fix.
Ravindra Wadile · · 0 likes