In Spring Data JPA, you can write an update query using the @Modifying and @Query annotations in a JPA Repository. Since JPA does not provide an out-of-the-box update method in repositories, you must define a custom query using JPQL (Java Persistence Query Language) or native SQL.
Steps
1. Use @Modifying to indicate a modifying query (such as UPDATE or DELETE).
2. Use @Query to define the update statement.
3. Use @Transactional to ensure the query runs within a transaction.
4. Use @Param to pass parameters.
@Repository
public interface UserRepository extends JpaRepository<User, Long>
{
@Modifying
@Transactional
@Query("UPDATE User u1 SET u1.status = :status WHERE u1.id = :id")
int updateUserStatus(@Param("id") Long id, @Param("status") String status);
}
Explanation
Steps
5. Annotate the method with @Modifying.
6. Use @Query with the parameter nativeQuery = true.
7. Ensure transactional context with @Transactional.
8. Define method parameters with @Param.
@Repository
public interface UserRepository extends JpaRepository<User, Long>
{
@Modifying
@Transactional
@Query(value = "UPDATE users SET status = :status WHERE id = :id", nativeQuery = true)
int updateUserStatusNative(@Param("id") Long id, @Param("status") String status);
}
Explanation
The nativeQuery = true flag tells JPA to use raw SQL instead of JPQL.
Ensure the table name (users) matches your actual database table.
Call this method from your service class:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void changeUserStatus(Long userId, String newStatus) {
userRepository.updateUserStatus(userId, newStatus);
}
}