1

Spring Data JPA allows you to define query methods by simply declaring their method signature" or, findByPropertyname gives you the correct object from the spring crud repository. Now, in my case, I need to update the database record which I can do by fetching it like above, then updating the properties of this object reference and finally persisting it using save(). The problem in this scenario is that while developing test case I am again fetching the object using the same property values. But the test case is failing due to the object already in updated state, which makes me ask: is this reference pointing to the same updated object?

Dog a=getrepository().findByProperty("property value");
a.setName("updated"); 
getrepository().save(a);

@Test 
Dog ia= getrepository().findByProperty("property value"); 
updated = 
callAboveCodeToTestUpdation(ia);
System.out.println("updated object prints same name as ia");
Prabhat Gaur
  • 146
  • 1
  • 10

1 Answers1

1

Yes, this is the behavior of JPA and is not really related to Spring Data. If you want the unmodified version you have to use a separate transaction.

From 3.1 EntityManager in the JPA specification (emphasize mine):

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348