有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring数据JPA findById()方法返回null而不是空可选

我有一个使用Spring数据的方法,JPA的findById()方法应该返回一个可选的。但是,如果指定的id找不到实体,它将返回null,而不是空的可选项

 public TicketEntity findTicket(String ticket) throws EntityNotFoundException {

    Optional<TicketEntity> op = ticketEntityRepository.findById(ticket);

    TicketEntity ticketEntity = op.orElseThrow(() -> new EntityNotFoundException("ticket with the id " + ticket + " not found in the system"));

    return ticketEntity;
}

调试时,我发现op的值为空。 这是一段失败的代码。我使用的是Spring数据JPA2.0.8。释放请帮忙


共 (3) 个答案

  1. # 1 楼答案

    代码行

    可选op=ticketEntityRepository。findById(票证)

    如果系统中存在数据,则返回结果集列表,否则很明显,它将返回null而不是空可选。 如果您需要一个空的可选列表,您可以按如下方式扭曲它

    List op=tickettentityrepository。findById(票证)。orElse(新ArrayList())

  2. # 2 楼答案

    在注释中,您声明这是在具有模拟依赖项的测试中。模拟完全消除了Spring数据JPA,因为它现在只是由来自Mockito的模拟实现的代理

    模拟的默认行为是返回null

    By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.

    当您使用模拟运行时,您需要指示它返回一个Optional.empty(),否则您将得到null

    注意:对于Optional返回类型,您可能希望为Mockito创建一个改进请求,以默认返回Optional.empty

  3. # 3 楼答案

    存储库类的实现是什么?下面的存储库和测试用例适合我

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class PersonRepoTest {
    
        @Autowired
        private PersonRepository personRepository;
    
        @Test
        public void testFindById(){
            Optional<Person> byId = personRepository.findById(1);
            Assert.assertTrue(byId != null);
        }
    }
    
    public interface PersonRepository  extends CrudRepository<Person, Integer> {
    }