Native SQL Queries
About
A Native SQL Query is a way to use SQL (Structured Query Language) directly within the JPA framework. Unlike JPQL or Criteria API, which are object-oriented and abstract from the underlying database, a Native SQL Query lets you write the exact SQL syntax (such as SELECT, INSERT, UPDATE, DELETE) specific to your relational database.
With native queries, you can execute complex SQL statements that might be difficult or impossible to express with JPQL or Criteria API, such as database-specific functions, complex joins, and performance optimizations (e.g., using database indexes or hints).
Characteristics
Direct SQL
You write raw SQL queries, exactly as you would in your database.
Database-Specific
Native SQL can be customized to specific database features and syntax.
No Object Mapping
Unlike JPQL, native queries work directly with tables and columns, not entities.
Performance Optimization
Allows fine-grained control for performance by using specific SQL optimizations (indexes, joins, etc.).
Flexibility
You can use all SQL features (like complex joins, unions, and aggregate functions).
Syntax Structure
In JPA, native SQL queries are executed using the EntityManager and createNativeQuery method.
Basic Syntax Example
String sql = "SELECT * FROM Employee WHERE department = :dept";
Query query = entityManager.createNativeQuery(sql);
query.setParameter("dept", "Sales");
List<Object[]> result = query.getResultList();Example with Native Query and Mapping to Entity
In this case, the Employee entity class is mapped to the result of the query.
Examples
Prerequisites
Entity Class - Employee.java
Repository Layer (EmployeeRepository.java)
1. Basic SELECT Query
Get all employees with salary greater than 50,000.
2. JOIN Query
Get employee names and their department names in the HR department.
3. Aggregations
Get the average salary of all employees.
4. Update Query
Increase salary by 5,000 for all employees in the IT department.
5. Delete Query
Delete employees who have not logged in since January 1, 2020.
6. Using SQL Functions
Get the highest salary from all employees.
7. Subqueries
Get all employees whose salary is above the average salary.
8. Batch Operations (Insert/Update/Delete)
Insert a new employee record into the database.
How Native SQL Queries Compare with JPQL and Criteria API ?
SQL Syntax
✅ Uses exact SQL syntax
❌ Does not use SQL syntax
❌ Does not use SQL syntax
Database-Specific
✅ Yes
❌ No
❌ No
Type-Safety
❌ No
❌ No
✅ Yes
Dynamic Query Support
✅ Yes
✅ Yes
✅ Yes
Portability
❌ Database-specific
✅ High
✅ High
Complex Queries
✅ Best
⚠️ Moderate
⚠️ Moderate
Last updated