0
0
Spring Bootframework~5 mins

Native SQL queries in Spring Boot

Choose your learning style9 modes available
Introduction

Native SQL queries let you run real SQL commands directly in your Spring Boot app. This helps when you want full control over the database or need special SQL features.

You want to write complex SQL that JPQL or Spring Data can't handle easily.
You need to use database-specific SQL functions or optimizations.
You want to run raw SQL for reporting or analytics queries.
You have an existing SQL query you want to reuse without rewriting.
You want to improve performance by writing optimized SQL.
Syntax
Spring Boot
@Query(value = "SQL query here", nativeQuery = true)
List<Entity> methodName();
Use @Query annotation with nativeQuery = true to tell Spring Boot this is raw SQL.
The SQL string is written exactly as you would run it in your database.
Examples
This finds a user by email using a native SQL query with a positional parameter.
Spring Boot
@Query(value = "SELECT * FROM users WHERE email = ?1", nativeQuery = true)
User findByEmail(String email);
This uses a named parameter to find products with price greater than a value.
Spring Boot
@Query(value = "SELECT * FROM products WHERE price > :minPrice", nativeQuery = true)
List<Product> findExpensiveProducts(@Param("minPrice") double minPrice);
Sample Program

This example shows a repository method using a native SQL query to get users by their status. The service calls it to print names of active users.

Spring Boot
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;

public interface UserRepository extends JpaRepository<User, Long> {

    @Query(value = "SELECT * FROM users WHERE status = :status", nativeQuery = true)
    List<User> findUsersByStatus(@Param("status") String status);
}

// Usage in a service class
@Service
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void printActiveUsers() {
        List<User> activeUsers = userRepository.findUsersByStatus("ACTIVE");
        activeUsers.forEach(user -> System.out.println(user.getName()));
    }
}
OutputSuccess
Important Notes

Make sure your SQL matches your database schema exactly.

Use parameters to avoid SQL injection risks.

Native queries bypass some JPA features like automatic mapping, so check your entity mappings carefully.

Summary

Native SQL queries let you run exact SQL in Spring Boot repositories.

Use @Query with nativeQuery = true and write your SQL as usual.

They are useful for complex or database-specific queries.