This guide shows how to run
native SQL queries in
Spring Boot with the
H2 database using Spring Data JPA.
1. Add Dependencies
In
pom.xml
:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2. Configure H2
In
application.properties
:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
3. Create Entity
import jakarta.persistence.*;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
}
4. Repository with Native Query
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
@Query(value = "SELECT * FROM CUSTOMER WHERE email = :email", nativeQuery = true)
Customer findByEmail(@Param("email") String email);
@Query(value = "SELECT * FROM CUSTOMER WHERE name LIKE %:name%", nativeQuery = true)
List<Customer> searchByName(@Param("name") String name);
}
5. Controller
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/customers")
public class CustomerController {
private final CustomerRepository repo;
public CustomerController(CustomerRepository repo) {
this.repo = repo;
}
@GetMapping("/by-email")
public Customer byEmail(@RequestParam String email) {
return repo.findByEmail(email);
}
@GetMapping("/search")
public List<Customer> search(@RequestParam String name) {
return repo.searchByName(name);
}
}
6. Run and Test
Start the app:
mvn spring-boot:run
GET /customers/by-email?email=test@mail.com
→ find by email
GET /customers/search?name=John
→ search customers by name
image quote pre code