Video in progress

When do you write a native SQL query instead of JPQL?

When you need something specific to the database: PostgreSQL jsonb operators, ON CONFLICT, special index hints, complex window functions, or optimized SQL handed over by a DBA. For plain CRUD and filters, JPQL is enough.

📖 Answer

@Query(value = """
        select * from products
        where attributes ->> 'color' = :color
        order by created_at desc
        limit 20
        """, nativeQuery = true)
List<Product> findByColor(@Param("color") String color);

A native query can return entities too, as long as the SELECT includes all of the entity's columns.

What you give up:

  • database independence: the query now works only on PostgreSQL;
  • Hibernate can't track the cache and flush well: after a native UPDATE/DELETE, the objects in the context go stale;
  • if you rename a field, neither the compiler nor Hibernate's startup check catches the native query, so the error appears only when it's called.

If you write a native UPDATE, put @Modifying(clearAutomatically = true) on it in Spring Data, so the persistence context is cleared and no stale data stays behind.

HQL got much stronger in Hibernate 6, so before switching to native it's worth checking whether you can write it in HQL.