Advertisement
Google Ad Slot: content-top
Spring Boot Named Queries
@NamedQuery allows defining reusable JPQL queries inside the entity class.
Example Entity Class
Let's assume we have a User entity with fields: id, name, email and age.
Table name : user
| id | name | age | |
|---|---|---|---|
| 1 | John | john@gmail.com | 25 |
| 2 | Mike | mike@gmail.com | 35 |
| 3 | Watson | watson@gmail.com | 40 |
| 4 | Kenny | kenny@gmail.com | 45 |
Create JPA Repositories
Create Services
Create Controllers
Testing the REST API with Postman:
Once the application is running, test the endpoints:
Get All Users GET:http://localhost:8080/users
Get User by Name GET:http://localhost:8080/users/{userName}
Get Users Older Than 30 GET:http://localhost:8080/users/older/{age}
Alternative: Named Native Queries (@NamedNativeQuery)
If you need raw SQL, use @NamedNativeQuery instead of @NamedQuery.