if you want to use the spring-data way, you have to use complex SQL/JPQL as less as possible.
@Entity
class CustomerEntity {
}
@Modifying
@Query("update CustomerEntity customer set customer.balance = :balance where customer.id = :customerId")
int updateCustomerBalance(@Param("customerId") String customerId, @Param("balance") String balance);
customerRepository.updateCustomerBalance("2", "400");
customerRepository.updateCustomerBalance("3", "150");
Common transaction
if you want to update happens in one transaction
@Transactional
void doUpdate() {
customerRepository.updateCustomerBalance("2", "400");
customerRepository.updateCustomerBalance("3", "150");
}
Keep in mind that you have to call service.doUpdate()
from outside. if you call the method from another service method, transaction will not be created.
Check that update has happened
int count = customerRepository.updateCustomerBalance("2", "400");
if (count == 0) {
log.error("Customer not updated customerId=2 customerBalance=400");
}