Why does getOne(…) on a Spring Data repository not throw an EntityNotFoundException?

后端 未结 2 556
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 10:43

I\'m working on a weird issue, I was doing integration testing, calling my controller to get an object from database that doesn\'t exist.

public Optional<         


        
2条回答
  •  青春惊慌失措
    2020-12-08 11:01

    In Spring @Repository classes, the getOne(id) method doesn't always verify existence until the object is queried (by calling entity.getId() or something) so it's no-such-entity exception may be delayed. To validate right away, use findById(id) instead (which returns an Optional which will be empty if the entity with that id doesn't exist).


    This is how it worked for me

    public User findUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
    

提交回复
热议问题