Search code examples
jakarta-eeredisspring-datahazelcastdistributed-caching

How to use multiple spring-data applications with a shared database


I have a spring application which uses spring-data to access a database. Now there is also another application, which needs to update the same database using just Hibernate/JPA to access the data.

If I update the data from the APP2, they will not be visible in the APP1 through the spring-data, because the underlying EntityManager would no be refreshed.

Is there any out-of-the-box solution how to provide this functionality? Obviously, what I can think of is:

  • create a common REST layer to provide these operations
  • Shared distributed cache like Hazelcast, Redis

I want to avoid the first option, because of the need to refactor the APP1. I am not sure about how the second would work, i.e.:

  • the shared objects between APP1 and APP2 would be stored in distributed cache and always read from there.
  • the updates would be executed through the respective access layer - the APP1 would use its spring-data repositories, the APP2 its Hibernate/JPA service (however, the EntityManager would still not be updated with possible changes from the other application).

Solution

  • After some digging around and testing, I've actually found out, that Spring-data together with Hibernate handles this situation correctly.

    I've based my test on pure Hibernate/JPA and when using two EntityManagers, correctly I didn't see the changes made through one of them in the another one (I created the EntityManager as a service class member during construction). However, what spring-data does is, that it opens a new Hibernate Session for every invocation of a @Transactional method and close it when it's done.

    So the problem rather is in the particular business logic, because it depends on the context of the @Transactional method if it is fine for it to "possibly" work with stale data during the invocation of the method.