Querying, from derived queries to JPQL, native SQL, CTEs, projections and JdbcClient
Every way your projects read data, when each is the right tool, plus SQL concepts (joins, aggregates, CTEs, window functions) you must be fluent in.
The spectrum
// 1. Derived query: Spring parses the method name
boolean existsByEmail(String email);
// 2. JPQL: queries entities and fields, not tables and columns
@Query("select u from User u where upper(u.email) = upper(:email)")
Optional<User> findByEmailIgnoreCase(String email);
// 3. Bulk update: skips the persistence context
@Modifying
@Query("UPDATE Booking b SET b.status = 'REJECTED' WHERE b.room.id = :roomId " +
"AND b.status = 'PENDING' AND b.id <> :approvedBookingId")
int rejectOtherPendingForRoom(UUID roomId, UUID approvedBookingId);
// 4. Native SQL: full Postgres power
@Query(value = "SELECT ... ST_Distance(...) ...", nativeQuery = true)
List<NearbyProjection> nearby(...);
// 5. JdbcClient: no JPA at all
jdbc.sql("SELECT account_id, SUM(debit) - SUM(credit) AS balance FROM journal_lines " +
"WHERE company_id = :c GROUP BY account_id")
.param("c", companyId).query(BalanceRow.class).list();
In your projects
repositories/UserRepository.javaDerived queries (existsByEmail) and simple JPQL (upper(u.email) = upper(:email)) for case-insensitive login.
HostelRepository.java (native CTE) · hostel/projection/*FlatProjection.javaA native query with a CTE (WITH ... AS) and conditional aggregation, projected into interfaces:
WITH RoomPeriodOccupancy AS (
SELECT room_id,
COUNT(CASE WHEN semester IN ('FIRST','FULL') THEN 1 END) AS first_sem,
COUNT(CASE WHEN semester IN ('SECOND','FULL') THEN 1 END) AS second_sem
FROM bookings
WHERE status IN ('APPROVED','CHECKED_IN') AND academic_year = :year
GROUP BY room_id
)
SELECT h.id, h.name, r.id AS room_id, r.capacity, COALESCE(o.first_sem,0) AS first_sem ...
FROM hostels h JOIN rooms r ON r.hostel_id = h.id
LEFT JOIN RoomPeriodOccupancy o ON o.room_id = r.idThe @Modifying bulk update rejectOtherPendingForRoom auto-rejects competing bookings once one is approved.
FinancialReportRepository.java · CashFlowStatementRepository.javaRM has 119 @Query methods, many native, because financial reports are aggregations (sums by unit, period and line), which SQL does far better than Java loops.
JdbcBalanceQuery · JdbcDocumentNumbers · RoleCatalogue · SsoStoreSperoTek mixes JPA (for aggregates with behaviour) and JdbcClient (for reporting, numbering and lookup tables). Balances, trial balance and statements are pure SQL.
SQL you must be fluent in
| Concept | Example |
|---|---|
| INNER vs LEFT JOIN | LEFT keeps hostels with zero bookings (COALESCE(o.first_sem, 0)) |
| GROUP BY / HAVING | GROUP BY account_id HAVING SUM(debit) <> SUM(credit) |
| Conditional aggregation | COUNT(*) FILTER (WHERE status='APPROVED') (Postgres) or CASE WHEN |
| CTEs | Named subqueries; WITH RECURSIVE for trees (e.g. RM’s ReportUnit hierarchy) |
| Window functions | Running balance: SUM(debit - credit) OVER (PARTITION BY account_id ORDER BY entry_date, id) |
| Subqueries / EXISTS | WHERE EXISTS (SELECT 1 FROM ...) is often faster than IN with large sets |
| UPSERT | INSERT ... ON CONFLICT (cart_id, product_id) DO UPDATE SET qty = cart_items.qty + 1 |
| RETURNING | INSERT ... RETURNING id |
Recursive CTE for RM’s unit tree
WITH RECURSIVE tree AS (
SELECT id, parent_id, name, 0 AS depth FROM report_units WHERE id = :root
UNION ALL
SELECT u.id, u.parent_id, u.name, t.depth + 1
FROM report_units u JOIN tree t ON u.parent_id = t.id
)
SELECT * FROM tree;
This loads a whole subtree in one query instead of walking getSubunits() recursively, which is N+1 again.
Related concepts you must know
- Parameter binding prevents SQL injection. Never concatenate user input into SQL. Every example above uses
:paramor?. @Modifyingbypasses the persistence context. Managed entities go stale, so useclearAutomatically = trueor reload them.- Projections. Interface-based (
getName()), class or record-based (new com.x.Dto(...)in JPQL), or dynamic. - Hostel’s
rejectOtherPendingForRoomcould have been an UPSERT/CTE in one round trip. Know both.