BBackend CourseLeroy Labs
0/0
Search the course

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.

● intermediateSpring-Boot-StoreHostel-Web-AppReport-Manager-2SperoTek (in dev)

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

Spring-Boot-Storerepositories/UserRepository.java

Derived queries (existsByEmail) and simple JPQL (upper(u.email) = upper(:email)) for case-insensitive login.

Hostel-Web-AppHostelRepository.java (native CTE) · hostel/projection/*FlatProjection.java

A 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.id

The @Modifying bulk update rejectOtherPendingForRoom auto-rejects competing bookings once one is approved.

Report-Manager-2FinancialReportRepository.java · CashFlowStatementRepository.java

RM 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.

SperoTek (in dev)JdbcBalanceQuery · JdbcDocumentNumbers · RoleCatalogue · SsoStore

SperoTek 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.

  • Parameter binding prevents SQL injection. Never concatenate user input into SQL. Every example above uses :param or ?.
  • @Modifying bypasses the persistence context. Managed entities go stale, so use clearAutomatically = true or reload them.
  • Projections. Interface-based (getName()), class or record-based (new com.x.Dto(...) in JPQL), or dynamic.
  • Hostel’s rejectOtherPendingForRoom could have been an UPSERT/CTE in one round trip. Know both.

Check yourself

1. Best tool for a trial balance (sum per account across 1M lines)?
2. Running balance per account ordered by date needs…
3. After a @Modifying bulk UPDATE, managed entities in the same transaction are…