javaspring-bootjpadatabase-replication

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

  • 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.