I have a Java, Spring Data application with a PostgreSQL DB and I have a code similar to this in my service layer:
public void method1() {
PersonDto dto = method2();
method3(dto);
}
@Transactional
public PersonDto method2() {
Person p1 = personRepository.saveAndFlush(new Person());
return createPersonDto(p1);
}
@Transactional
public void method3(PersonDto p1) {
Person p2 = personRepository.findById(p1.getId());
if (p2 == null) {
System.out.println("Not in the DB");
} else {
System.out.println("In the DB");
}
}
Sometimes this code prints "Not in the DB", when I was expecting that it would always print "In the DB". My questions are:
- This saveAndFlush is even necessary? Since I'm not reusing that Entity in the same transaction, I guess it would have the same effect as a save, right?
- How to guarantee that the changes in method2 will be committed before method 3 calls it? So it will always print "In the DB"?
- The fact that I'm converting my Entity to a DTO is what is messing this up? Maybe if I was passing the Entity itself it would work properly?
I'm thinking about @Transactional only in method1, or replacing @Transactional in method3 with @Transactional(isolation = Isolation.READ_UNCOMMITTED). Any advice?