Spring 事务注解回滚测试似乎不太顺利

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

这是控制器代码:

@GetMapping("/test/hello")
    public String test()  {
        Member m = memberService.transactionTest();
        return "haha";
    }

这是服务代码:

   @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();
    }

据我所知,当它完成时应该回滚 因为发生了RuntimeException,但是插入过程运行良好所以我想知道为什么。

因为 Optional.get() 抛出 NoSuchElementException (而不是空指针)。

From javadoc:

public T get()

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

通过 rollbackFor = NullPointerException.class 您将 NoSuchElementException 从可回滚异常中排除。