Spring Data JPA - @Modifying Annotation
Last Updated :
05 Apr, 2024
@Modifying annotation in Spring Data JPA allows modification queries such as update and delete and enhances the capabilities of the @Query annotation. It enables data transformation actions beyond simple data retrieval, ensuring transaction integrity and improving performance.
The @Modifying annotation is used to enhance the @Query annotation so that we can not only execute the SELECT queries, but also INSERT, UPDATE, DELETE, and even DDL queries that modify the structure of the underlying database schema using Spring Data JPA
Benefits of @Modifying Annotation
@Modifying annotation is used when you want to execute modifying queries, such as updates or deletes. This annotation is necessary because, by default, Spring Data JPA repository methods are considered read-only and are optimized for querying data, not modifying it.
- Improved Performance: Improves performance by allowing changing queries to be executed.
- Transactional Integrity: Ensures transaction integrity while performing data changes.
- Support for native queries: Enables native queries for data transformation.
- Automatic Flush and Clear: Supports automatic flushing and clearing of durability references.
Implementation of @Modifying Annotation of Spring Data JPA
Step 1: Define Entity Class
Define an entity class named User that contains fields such as id, name, age, and isActive to represent user data.
Java
@Entity
@Data
public class User {
// Primary key
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
// User's name
private String name;
// User's age
private int age;
// Indicates if the user is active
@Column(name="active")
private Boolean isActive = true;
}
Step 2: Define Repository Interface
Now we will create a repository interface named UserDao that extends JpaRepository with @Modifying and is annotated with @Query annotation to perform update actions.
Java
@Repository
public interface UserDao extends JpaRepository<User, Integer>{
// Modifying query to update user's active status based on age
@Modifying
@Query(nativeQuery = true, value = "update user u set u.active=0 where u.age < :age")
void updateUser(@Param("age") int age);
}
Step 3: Create Service Class
Now create one class named UserserviceDemo. Inside this class, call the updateUser method that will update data in the database.
Java
@Service
public class UserServiceDemo {
@Autowired
private UserDao userDao;
//get user data from database..
public List<User> getUserDetail() {
return userDao.findAll();
}
//update user data using our custom method..
public String updateUserDetail(int age) {
userDao.updateUser(age);
return "successfully update !!";
}
}
Step 4: Implement Controller
Inside the controller, create one class named UserControllerDemo to process HTTP requests, including using endpoints to retrieve user data and update user information.
Java
@RestController
public class UserControllerDemo {
// Autowired UserServiceDemo bean
@Autowired
private UserServiceDemo userServiceDemo;
// GET endpoint to retrieve user data
@GetMapping("user")
public List<User> getUser() {
return userServiceDemo.getUserDetail();
}
// PUT endpoint to update user details based on age
@PutMapping("updateuser/{age}")
public String updateUser(@PathVariable int age) {
return userServiceDemo.updateUserDetail(age);
}
}
Step 5: Run the application
Now we will run the application and verify the update and delete operations, ensuring successful modification of data in the database.
Output:
Update activation status: false where age less than 20
Here, we can see the status update properly in the database.

The above is updating data using the @Modifying annotation. If we have to delete data from the database using the @Modifying annotation, then add the below method to the repository.
@Modifying
@Query(nativeQuery = true,value = "delete from user u where u.active = false")
void deleteDeactivatedUsers();
It can successfully delete data from a database where the activation status is false.

Here, we can see the data was properly deleted in the database.

We can see updates and deletes using the @Modifying annotation. Now we can work with DDL queries using the @Modifying annotation, which means alter, drop, etc.
@Modifying
@Query(value = "alter table user u drop column u.login_date", nativeQuery = true)
void deletedColumn();
The above method can be used to drop/delete a column from a database that will be unnecessary in the table. Now we can alter the table using the @Modifying annotation.
Output:
Before executing the above method, the login_date column is unnecessary in database table.

Now, we can execute the deleteColumn() method.
.png)
After executing the method, we can see the column was successfully deleted.

Similar Reads
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read
Spring Tutorial Spring Framework is a comprehensive and versatile platform for enterprise Java development. It is known for its Inversion of Control (IoC) and Dependency Injection (DI) capabilities that simplify creating modular and testable applications. Key features include Spring MVC for web development, Spring
13 min read
Introduction to JSP JavaServer Pages (JSP) is a server-side technology that creates dynamic web applications. It allows developers to embed Java code directly into HTML or XML pages, and it makes web development more efficient.JSP is an advanced version of Servlets. It provides enhanced capabilities for building scalab
5 min read
Introduction to Spring Boot Spring is widely used for creating scalable applications. For web applications, Spring provides Spring MVC, a commonly used module for building robust web applications. The major drawback of traditional Spring projects is that configuration can be time-consuming and overwhelming for new developers.
5 min read
Spring Boot - Annotations Spring Boot Annotations are a form of metadata that provides data about a spring application. Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the
7 min read
Java AWT Tutorial Java AWT or Abstract Window Toolkit is an API used for developing GUI(Graphic User Interfaces) or Window-Based Applications in Java. Java AWT is part of the Java Foundation Classes (JFC) that provides a way to build platform-independent graphical applications.In this AWT tutorial, you will learn the
13 min read
Introduction to Spring Framework The Spring Framework is a powerful, lightweight, and widely used Java framework for building enterprise applications. It provides a comprehensive programming and configuration model for Java-based applications, making development faster, scalable, and maintainable.Before Enterprise Java Beans (EJB),
9 min read
Java Microservices Interview Questions and Answers Microservices, also called Microservices Architecture, is a software development approach that involves building large applications as a collection of small functional modules. This architectural approach is widely adopted due to its ease of maintenance and faster development process. Microservices
15+ min read
Spring Boot 3.0 - JWT Authentication with Spring Security using MySQL Database In Spring Security 5.7.0, the Spring team deprecated the WebSecurityConfigurerAdapter, as they encourage users to move towards a component-based security configuration. Spring Boot 3.0 has come with many changes in Spring Security. In this article, we are going to learn how to implement JWT authenti
8 min read