JpaRepository QueryByExample方法使用详解

spring-data-jpa从1.12版本开始,JpaRepository继承的接口由之前的CrudRepository,PagingAndSortingRepository改为了QueryByExampleExecutor,PagingAndSortingRepository。这其中的变化主要就是CrudRepository接口换成了QueryByExampleExecutor接口。

QueryByExampleExecutor接口用了Java 1.8增加的Optional 用以优雅的解决NullPointException 的问题。从而导致JpaRepository中之前类似于

 T findOne(ID id);

方法定义修改为

Optional<S> findOne(Example<S> example);

即传参和回调分别改为了Example和Optional。因此方法使用与之前不同。

之前调用findOne方法只需简单一行即可。

public User getOne(String id) {
     return userRepository.findOne(id);  
}

现在则需要先封装成一个Exmple再传参进行查询。

public User getOne(String id) {
     User user = new User();
     user.setId(id);
     Example<User> userExample = Example.of(user);
     return userRepository.findOne(userExample).orElse(null); 
}

而且返回的是一个Optional类,关于Optional类具体的解释就不贴出来了,以下是几种关于Optional获取实体类的实用方法。

  • 存在即返回, 无则提供默认值

    return user.orElse(null);  //而不是 return user.isPresent() ? user.get() : null;
    return user.orElse(UNKNOWN_USER);
  • 存在即返回, 无则由函数来产生

    return user.orElseGet(() -> fetchAUserFromDatabase()); //而不要 return user.isPresent() ? user: fetchAUserFromDatabase();
  • 存在才对它做点什么

    user.ifPresent(System.out::println);
     
    //而不要下边那样
    if (user.isPresent()) {
      System.out.println(user.get());
    }
原文地址:https://www.cnblogs.com/magotzis/p/8259998.html