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 will explain two cases, both of them have only one difference which shouldn't make any difference but it's causing some unusual behaviour.
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.
Now the following is happening in two different cases:
CASE 1:
class MainClass {
@Autowired
AutowiredClass1 autowiredClass1;
public void main() {
//inital object after first repository call
Object obj1 = repo.findById(id);
//make some changes in obj1
funcInTheSameClass(obj1);
repo.saveAndFlush(obj1)
log.info(obj1); //here also obj1 name is still null
}
void funcInTheSameClass(Object obj1) {
autowiredClass1.funcInAutowiredClass1(obj1);
log.info(obj1); //here also obj1 name is still null
}
}
class AutowiredClass1 {
@Autowired
AutowiredClass2 autowiredClass2;
public void funcInAutowiredClasss1(Object obj1) {
autowiredClass2.funcInAutowiredClass2(obj1.id);
log.info(obj1); // now here the obj1 name is still null
}
}
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"
}
}
CASE 2:
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 there is a difference of one repo call only and it's working in different ways. In the first case, the value of obj1 is not reflected back from funcInAutowiredClass2 to the main function. But in the second case, the value of obj1 is updated. How is this happening?