'Can I set readOnly false when I use findById with JPA
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?
+++) I solved my problem! I wanted to use dirty checking for modifying datas and I realized that my setting about EntityManagerFactory was something wrong and I fixed it with a doc in spring.io (https://docs.spring.io/spring-data/jpa/docs/current-SNAPSHOT/reference/html/#reference) I tried many times with many other developers posting but they didn't work for me, but it did. Thank you for giving me answers 😭
Solution 1:[1]
Refer this,
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#transactions
Section 5.7.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.
Solution 2:[2]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Aleksandar Gordic. |
