You can use Spring Data JPA’s @ Modifying and @ Query annotations to achieve Update a field of a Table using Sping Repository Modifying Query.
Spring Repository
Here is an example:
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.transaction.annotation.Transactional;public interface UserRequestRepository extends CrudRepository<UserRequest, Long> { @Modifying @Query("UPDATE UserRequest u SET u.fieldCount = 0") void updateFieldCountToZero(); }
Note that the entity name is UserRequest and the field name is fieldCount.
Spring Service
Also, remember to add @Transactional annotation on your service method where you’re calling the repository’s update method, to ensure that the changes are committed to the database.
@Service
public class MyService {
@Autowired
private UserRequestRepository userRequestRepository;
public void updateFieldCountToZero() {
userRequestRepository.updateFieldCountToZero();
}
}
@Service
@Transactional
public class MyService {
@Autowired
private UserRequestRepository userRequestRepository;
public void updateFieldCountToZero() {
userRequestRepository.updateFieldCountToZero();
}
}
After all the above, you could inject the service to a @RestController or a Web @Controller. I personally use it in a Vaadin Web App. You could see some of the ready ones here: https://programtom.com/dev/product-category/technologies/spring-boot-framework/?orderby=date-desc
