This is the Controller code:
@GetMapping("/test/hello")
public String test() {
Member m = memberService.transactionTest();
return "haha";
}
and this is Service code:
@Transactional(rollbackFor = NullPointerException.class)
public Member transactionTest() {
Member m = Member.builder()
.username("rollback")
.age(32)
.team(teamRepository.findById(1L).get())
.coach(coachRepository.findById(1L).get())
.build();
memberRepository.save(m);
exception();
return m;
}
public void exception(){
Member m = null;
m.getUsername();
}
As far as I know when it finishes it should rollback because RuntimeException occurs but insert process works so well so I want to know why.
CodePudding user response:
Because Optional.get()
throws NoSuchElementException
(and not null pointer).
public T get()
If a value is present in this
Optional
, returns the value, otherwise throwsNoSuchElementException
....
By rollbackFor = NullPointerException.class
you exclude NoSuchElementException
from rollback-able exceptions.