I know the title is quite confusing and so is the question. I was working on spring boot with the JPA repository and some unusual behaviour happened.
I made a repository call to get an object, let's say obj1 and I made some changes on it and then I passed obj1 to another function funcInSameClass(obj1) which is in the same class and from that function I passed the obj1 to a function funcInAutowiredClass1(obj) of an autowired component AutowiredClass1, from that component I passed the Id of obj1 to another function funcInAutowiredClass2(obj1.id) of autowired component AutowiredClass2. And in funcInAutowiredClass2(obj1.id) I made a repository call to get the same object as obj1 and make some changes in obj1 and saveAndFlush to the database.
class MainClass {
@Autowired
AutowiredClass1 autowiredClass1;
public void main() {
//inital object after first repository call
Object obj1 = repo.findById(id);
//make some changes in obj1
obj1 = repo.saveAndFlush(obj1);
funcInTheSameClass(obj1);
repo.saveAndFlush(obj1)
log.info(obj1); //here also obj1 name is now XYZ
}
void funcInTheSameClass(Object obj1) {
autowiredClass1.funcInAutowiredClass1(obj1);
log.info(obj1); //here obj1 name is now XYZ
}
}
class AutowiredClass1 {
@Autowired
AutowiredClass2 autowiredClass2;
public void funcInAutowiredClasss1(Object obj1) {
autowiredClass2.funcInAutowiredClass2(obj1.id);
log.info(obj1); // now obj1 name is now XYZ
}
}
class AutowiredClass2 {
public void funcInAutowiredClasss2(int id) {
Object obj2 = repo.findById(id);
obj2.setName("XYZ");
repo.saveAndFlush(obj2);
log.info(obj2); // here I set the obj2 name as "XYZ"
}
}
You can see that in the funcInAutowiredClass2, reference of obj1 is not passed but a fresh entity is fetched from the repository and updated and saved. Then how come the changes reflect back in main function().