Video in progress

Middle 🌱 Spring

What's the difference between writing a JPQL query and a native SQL query with @Query?

JPQL is written with entity and field names and isn't tied to a database. Native SQL uses tables and columns and unlocks the database's own features (window functions, JSONB, CTEs), but it won't port to another database.

📖 Answer

// JPQL — entity names
@Query("select o from Order o where o.customer.id = :cid and o.status = :st")
List<Order> findActive(@Param("cid") long cid, @Param("st") Status st);

// Native — table names, PostgreSQL features
@Query(value = """
        select * from orders
        where data ->> 'channel' = :channel
        order by created_at desc limit 50
        """, nativeQuery = true)
List<Order> byChannel(@Param("channel") String channel);

When you need native: window functions, ON CONFLICT, JSONB, recursive CTEs, a carefully hand-tuned query.

Modifying queries:

@Modifying(clearAutomatically = true)
@Query("update Product p set p.price = p.price * :k where p.category = :c")
int reprice(@Param("k") BigDecimal k, @Param("c") String c);

This query bypasses the persistence context — stale entities in memory don't get updated, which is what clearAutomatically is for. It must be called inside a transaction.

In both cases pass values only as parameters — build a query by concatenating strings and you open the door to SQL injection.