1

everyone! I have a problem. I use Spring Data in my project with some microservices. One of them changes a row in DB. Then in my microservice I check that row. The main problem is that findById() method of Spring Data return old, not changed value. I put a breakpoin, my eyes see one value in DB, but repository give me another one. After some experiments I decided to try to write this query throught Spring JBDC. And now - everything is okay. This is Spring Data query:

Optional<MessageLog> byId = messageLogRepository.findById(id);

This is Spring JDBC:

public MessageLog findByIdJdbc(String id) {
    SqlParameterSource sqlParameterSource = new MapSqlParameterSource("id", id);
    String findByIdSQL = "SELECT * from MESSAGESLOG where ID = :id";
    return namedParameterJdbcTemplate.queryForObject(findByIdSQL, sqlParameterSource, rowMapper);
    }

Could you, please, give me an explanation or an article? I think that the problem can be in cache. But did not find an answer.

Andrej Istomin
  • 2,527
  • 2
  • 15
  • 22
Vitaliy
  • 25
  • 7
  • does this help? https://stackoverflow.com/questions/51739841/how-to-disable-spring-hibernate-hazelcast-joint-cache – J Asgarov Mar 09 '23 at 11:24
  • @JAsgarov no. I don't use second level cache. As I know it is disable by default. But thank you! – Vitaliy Mar 09 '23 at 12:03
  • 1
    will this help? https://stackoverflow.com/questions/7933617/getting-old-data-with-jpa – JavaLearner1 Mar 09 '23 at 12:15
  • 1
    Could you try clearing the entityManager before calling findById to see what happens: entityManager.clear(); – Marc Bannout Mar 09 '23 at 13:24
  • @JavaLearner1, Meac Bannout thank you! Now it's work. But could you give me a complete explanation? As I understand Hibernate has first level cache or PersistenceContext which save all entities in one session. I had it in one state, then another micoservice changes the row in DB, but I still got the the same entity. entityManager.clear() - clear this context and everything is fine. But as I understand in my case: Spring JDBC works with DB directly? And as I use Spring data through CrudRepository I needed to add "EntityManager entityManager". Is it a good way? Or I can use some annotation? – Vitaliy Mar 09 '23 at 14:33

1 Answers1

0

As guys in comments said: I need to write:

entityManager.clear()
Vitaliy
  • 25
  • 7