Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 858
유호연 Avatar asked Dec 06 '25 18:12

유호연


1 Answers

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.

like image 66
xerx593 Avatar answered Dec 08 '25 08:12

xerx593



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!