Understanding @Modifying Annotation in Spring Boot with a Step-by-Step Example
Introduction
In Spring Data JPA, the @Modifying
annotation is essential when executing update or delete operations using JPQL or native queries. It signals to Spring that the query will change data rather than just retrieving it.
In this post, we’ll explore how to use @Modifying
effectively with a working example.
Why Use @Modifying Annotation?
By default, Spring Data JPA repositories handle read operations. However, when executing update or delete queries, Spring needs a hint that these queries modify records. The @Modifying
annotation:
- Enables
update
anddelete
operations. - Ensures transaction management works correctly.
- Helps execute queries without expecting a return value.
Step-by-Step Guide
1. Set Up Entity Class
First, define a simple Employee
entity.
@Entity @Table(name = "employees") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String department; // Getters and Setters }
2. Create Repository Interface
Define an interface that extends JpaRepository
. Here, we declare an update query using @Modifying
.
@Repository public interface EmployeeRepository extends JpaRepository<Employee, Long> { @Modifying @Query("UPDATE Employee e SET e.department = :department WHERE e.id = :id") int updateDepartment(@Param("id") Long id, @Param("department") String department); }
3. Implement Service Layer
We create a service layer to call the repository method.
@Service @Transactional public class EmployeeService { @Autowired private EmployeeRepository employeeRepository; public void changeDepartment(Long id, String newDepartment) { employeeRepository.updateDepartment(id, newDepartment); } }
4. Create a REST Controller
Expose an API to update employee department.
@RestController @RequestMapping("/employees") public class EmployeeController { @Autowired private EmployeeService employeeService; @PutMapping("/{id}/department") public ResponseEntity<String> updateDepartment(@PathVariable Long id, @RequestParam String department) { employeeService.changeDepartment(id, department); return ResponseEntity.ok("Employee department updated successfully!"); } }
5. Test the Endpoint
Use Postman or curl
to test the API:
curl -X PUT "http://localhost:8080/employees/1/department?department=HR"
If successful, the response should be:
{ "message": "Employee department updated successfully!" } </code>
Conclusion
The @Modifying
annotation is crucial when performing update or delete queries in Spring Data JPA. By following this guide, you can efficiently modify records using JPQL queries within repository interfaces.
Want to explore batch updates or native queries with @Modifying
? Let me know!