好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring Boot2.X中findOne的使用详解

Spring Boot2.X中findOne的用法

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

?

1

xxxRepository.findOne(id);

但在2.X中,findOne改为了

?

1

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

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

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

?

1

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)方法

?

1

2

T findOne(ID id);

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

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

下面是解决办法

?

1

2

3

4

5

6

7

8

9

10

11

12

13

@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 ;

      }

  }

记录一下,方便查询!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/TMaskBoy/article/details/91489433

查看更多关于Spring Boot2.X中findOne的使用详解的详细内容...

  阅读:15次