SpringDataJPA中findOne和getOne的区别

发现

SpringDataJPA和Hibernate有很多异曲同工之处,比如这个根据主键获取某条数据的函数:findOne() 和 getOne(),有时候没有区特别注意这两个获取单条数据的方法,结果有时候测试发现 getOne 获取不到数据就报错。

代码

首先我们看一下它们的注解

 /**
   * Retrieves an entity by its id.
   * 
   * @param id must not be {@literal null}.
   * @return the entity with the given id or {@literal null} if none found
   * @throws IllegalArgumentException if {@code id} is {@literal null}
   */
  T findOne(ID id);
/**
   * Returns a reference to the entity with the given identifier.
   * 
   * @param id must not be {@literal null}.
   * @return a reference to the entity with the given identifier.
   * @see EntityManager#getReference(Class, Object)
   */
  T getOne(ID id);

结果

  • findOne:查询一个不存在的id数据时,返回的值是null.
  • getOne:查询一个不存在的id数据时,直接抛出异常,因为它返回的是一个引用,简单点说就是一个代理对象。

所以说,如果想无论如何都有一个返回,那么就用findOne,如果是需要报错抛出异常的场景就使用getOne。

猜你喜欢

转载自blog.csdn.net/moshowgame/article/details/80695404