Performance: Native SQL queries
Native SQL queries impact server response time and data fetching speed, which affects how fast the page can start rendering.
Jump into concepts and practice - no test required
String sql = "SELECT id, name, email FROM users WHERE active = true LIMIT 100"; List<User> users = entityManager.createNativeQuery(sql, User.class).getResultList();
String sql = "SELECT * FROM users"; List<User> users = entityManager.createNativeQuery(sql, User.class).getResultList();
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Fetching all data without filters | N/A (server-side) | N/A | Delays initial paint | [X] Bad |
| Fetching filtered, limited data | N/A (server-side) | N/A | Speeds up initial paint | [OK] Good |
@Query annotation is used to define custom queries in repository interfaces.nativeQuery = true inside @Query tells Spring Boot to treat the query as native SQL.value, and to mark it native SQL, use nativeQuery = true.@Query(value = "...", nativeQuery = true). Options B, C, and D use invalid attribute names or annotations.@Query(value = "SELECT * FROM products WHERE price > ?1", nativeQuery = true) List<Product> findExpensiveProducts(double minPrice);
findExpensiveProducts(100.0)?findExpensiveProducts(100.0) returns products priced above 100.0, so the list contains those products.@Query(value = "SELECT * FROM orders WHERE status = :status", nativeQuery = true) List<Order> findByStatus(String status);
:status by default; they require positional parameters like ?1.?1 to refer to the first method parameter instead of :status.@Modifying annotation to indicate a modifying operation.?1 and sets nativeQuery = true. @Modifying
@Query(value = "UPDATE products SET price = price * 1.1 WHERE category = :category", nativeQuery = true)
int increasePriceByCategory(String category); uses named parameter which is invalid in native queries. @Modifying
@Query(value = "UPDATE products SET price = price * 1.1 WHERE category = ?1")
int increasePriceByCategory(String category); misses nativeQuery flag. @Query(value = "UPDATE products SET price = price * 1.1 WHERE category = ?1", nativeQuery = true)
void increasePriceByCategory(String category); misses @Modifying.