Search code examples
javaspring-boothibernatejpatransactions

Spring transactional annotation rollback test doesn't seem to go well


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.


Solution

  • Because Optional.get() throws NoSuchElementException (and not null pointer).

    From javadoc:

    public T get()

    If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException....

    By rollbackFor = NullPointerException.class you exclude NoSuchElementException from rollback-able exceptions.