Spring Boot2.X中findOne的用法

本篇内容介绍了“Spring Boot2.X中findOne的用法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

目录
  • Spring Boot2.X中findOne的用法

    • 但在2.X中,findOne改为了

  • JpaRepository.findOne()在springboot1.x和2.x中的不同的用法

    • 在使用springboot 1.5.6.RELEASE时

    • 2.x版本已无法使用 T findOne(ID id)

Spring Boot2.X中findOne的用法

SpringBoot在1.5.X版本中,传入id即可查询对象

xxxRepository.findOne(id);

但在2.X中,findOne改为了

<S extends T> Optional<S> findOne(Example<S> var1);

getOne方法继续保留了,但是如果getOne(id)查询到的即使id不存在,也会返回该对象的引用,判断null无效。

后来找到了这种写法可以实现

findOne. xxxRepository.findById(id).orElse(null)

JpaRepository.findOne()在springboot1.x和2.x中的不同的用法

已有开发环境如下

  • Windows平台

  • jdk1.8、maven已配置

  • 开发工具:Intellij IDEA

在使用springboot 1.5.6.RELEASE时

JpaRepository支持findOne(ID)方法

T findOne(ID id);
<S extends T> Optional<S> findOne(Example<S> example);

2.x版本已无法使用 T findOne(ID id)

下面是解决办法

 @Override
 public AyUser selectAyUserById(Integer id) {
      AyUser ayUser = new AyUser();
      ayUser.setId(id);
      Example<AyUser> example = Example.of(ayUser);        
      Optional<AyUser> optional = ayUserRepository.findOne(example);
      if (optional.isPresent()){
          ayUser=optional.get();
          return  ayUser;
      }else{
          return  null;
      }
  }

“Spring Boot2.X中findOne的用法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!