I have a problem with modifying data while setting database replication
Before DB replication, I get data that I want to modify using repository.findById()
and then I modified the data.
But I realized that repository.findById()
is set @Transactional(readOnly = true)
in SimpleJpaRepository.java
so that I can't modify the data even if I use @Transactional in my Service or repository.save()
Is there any other way to force findById()
to connect by a write connection except by making custom method in the repository for findById?
CodePudding user response:
Refer this,
https://docs.spring.io/spring-data/data-jpa/docs/1.0.0.M1/reference/html/#transactions
Section 2.3.1. Transactional query methods to be more specific
It says that @Modifying annotation can be used to override transaction configuration
Typically you will use the readOnly flag set to true as most of the query methods will be reading ones. In contrast to that deleteInactiveUsers() makes use of the @Modifying annotation and overrides the transaction configuration. Thus the method will be executed with readOnly flag set to false.
CodePudding user response:
You don't need to change that flag!
- Find the data
- Edit data
- Call JPA repository.save(newData) method with @Modifying to save the edited data in the DB
I.E.
@Transactional
@Modifying
@Query(value = "UPDATE user SET points = points ?1
WHERE id = ?2", nativeQuery = true)
int increasePoints(int points, Long id);