JPQL (Java Persistence Query Language) is a Hibernate-based query language used to retrieve data from the database in Spring Data JPA. It is similar to SQL but operates on entity objects instead of database tables.
Example Entity Class
Let's assume we have a Userentity with fields: id, name, email and age.
User.java
import jakarta.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private int age;
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Table name : user
id
name
email
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
Example
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 {
// ✅ Find All Users
@Query("SELECT u FROM User u") // Optional Jpa write for you
List findAllUsers();
// ✅ Find User by Name
@Query("SELECT u FROM User u WHERE u.name = :name") // Optional Jpa write for you
User findByName(@Param("name") String name);
// ✅ Find Users by Age Greater Than
@Query("SELECT u FROM User u WHERE u.age > :age") // Optional Jpa write for you
List findUsersOlderThan(@Param("age") int age);
// ✅ Find User by Email (Native Query)
@Query(value = "SELECT * FROM user WHERE email = :email", nativeQuery = true) // Native query
User findByEmail(@Param("email") String email);
// ✅ Update User Email by ID
@Modifying
@Transactional
@Query(value = "UPDATE user SET email = :email WHERE id = :id", nativeQuery = true) // Native query
int updateUserEmail(@Param("id") Long id, @Param("email") String email);
// ✅ Delete User by ID
@Modifying
@Transactional
@Query(value = "DELETE FROM user WHERE id = :id", nativeQuery = true) // Native query
int deleteUserById(@Param("id") Long id);
}
findAllUsers , findByName , findUsersOlderThan optional queries you don't want to write Jpa write query for you
Create Services
UserService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
// ✅ Get All Users
public List getAllUsers() {
return userRepository.findAllUsers();
}
// ✅ Get User by Name
public User getUserByName(String name) {
return userRepository.findByName(name);
}
// ✅ Get Users Older Than Age
public List getUsersOlderThan(int age) {
return userRepository.findUsersOlderThan(age);
}
// ✅ Update User Email
public int updateUserEmail(Long id, String email) {
return userRepository.updateUserEmail(id, email);
}
// ✅ Delete User by ID
public int deleteUser(Long id) {
return userRepository.deleteUserById(id);
}
}
Create Controllers
UserController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
// ✅ Get All Users
@GetMapping
public ResponseEntity> getAllUsers() {
return ResponseEntity.ok(userService.getAllUsers());
}
// ✅ Get User by Name
@GetMapping("/{name}")
public ResponseEntity getUserByName(@PathVariable String name) {
return ResponseEntity.ok(userService.getUserByName(name));
}
// ✅ Get Users Older Than Age
@GetMapping("/older/{age}")
public ResponseEntity> getUsersOlderThan(@PathVariable int age) {
return ResponseEntity.ok(userService.getUsersOlderThan(age));
}
// ✅ Update Email
@PutMapping("/{id}/email")
public ResponseEntity updateUserEmail(@PathVariable Long id, @RequestBody String email) {
int rowsUpdated = userService.updateUserEmail(id, email);
return ResponseEntity.ok(rowsUpdated + " row(s) updated.");
}
// ✅ Delete User
@DeleteMapping("/{id}")
public ResponseEntity deleteUser(@PathVariable Long id) {
int rowsDeleted = userService.deleteUser(id);
return ResponseEntity.ok(rowsDeleted + " row(s) Deleted.");
}
}
Advanced JPQL Queries
JPQL with Sorting
@Query("SELECT u FROM User u ORDER BY u.age DESC")
List findAllUsersSortedByAge();
JPQL with LIKE (Search by Name)
@Query("SELECT u FROM User u WHERE u.name LIKE %:keyword%")
List searchUsersByName(@Param("keyword") String keyword);
JPQL with COUNT
@Query("SELECT COUNT(u) FROM User u WHERE u.age > :age")
Long countUsersOlderThan(@Param("age") int age);
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}
We use cookies and similar technologies to enhance your browsing experience, serve personalized content and advertisements, and analyze our traffic.
By clicking "Accept All", you consent to our use of cookies and the processing of your personal data for these purposes.
You can manage your preferences or learn more in our
Privacy Policy and
Cookie Policy.