Spring|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改为了
Optional findOne(Example 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时
【Spring|Spring Boot2.X中findOne的使用详解】JpaRepository支持findOne(ID)方法
T findOne(ID id); Optional findOne(Example example);


2.x版本已无法使用 T findOne(ID id)
下面是解决办法
@Override public AyUser selectAyUserById(Integer id) {AyUser ayUser = new AyUser(); ayUser.setId(id); Example example = Example.of(ayUser); Optional optional = ayUserRepository.findOne(example); if (optional.isPresent()){ayUser=optional.get(); returnayUser; }else{returnnull; }}

记录一下,方便查询!
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读