bove
bove

Reputation: 43

Spring Data entity synchronization

I am using Spring Data to access a relational database, here pseudo code:

@Repository
public interface UserRepository extends JpaRepository<User, BigDecimal> {
    public User findByName(String name);
...
}

@Entity
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class User {
    @Column(...)
    @EqualsAndHashCode.Include
    private String name;
...
}

Now my question is: If I call UserRepository#findByName several times, I get each time a different Java object - of course containing the same data. Is this intentional? And if I apply changes to one such instance the other one doesn't get the update. In an ideal scenario I wanted to either have the same object for the same entity or at least have the objects synchronized.

Upvotes: 1

Views: 2019

Answers (1)

  • Lets say you have a service like this
    @Service
    public class ServiceA {
       
       @Autowired
       private UserRepository userRepository
       
       @Transactional
       public User findByNameWithTransactionHereTimes(String name){
          User user1 = userRepository.findByName(name);
          User user2 = userRepository.findByName(name);
          // user1 == user2 will be true and I am comparing by reference
          
       }

       //
       public User findByNameWithNoTransactionHere(String name){
          User user1 = userRepository.findByName(name);
          User user2 = userRepository.findByName(name);
          // user1 != user2 will be true and I am comparing by reference
          
       }
    ...
    }
  • Hibernate guarantees Repeatable read within session and it can act as cache.

  • In the first method, a session opened when the transaction started and it is closed when the transaction completes so hibernate gives you Repeatable read

  • In the second method, a session opened when you called userRepository.findByName and closed when it returns. It happens again, when you call it second time. Since the previous session was closed, hibernate does not have any memory of it and returns the new object

Upvotes: 4

Related Questions