Spring Data JPA 之 getOne() 和 findOne() 的区别

avatar 2018年03月30日23:25:47 6 4340 views
博主分享免费Java教学视频,B站账号:Java刘哥
在使用 SpringDataJPA 过程中,但是发现它和Hibernate有很多相似之处,比如这个根据主键获取某条数据的函数:findOne() 和 getOne(),就很像Hibernate中的load和get. 之前没有特别注意这两个获取单条数据的方法,所以找了一个带One的就用,结果有时候测试发现 getOne 一直在报错,经过多次查找原因,发现原来是 getOne 导致的。 首先我们看一下它们的注解
  1.  /**
  2.    * Retrieves an entity by its id.
  3.    * 
  4.    * @param id must not be {@literal null}.
  5.    * @return the entity with the given id or {@literal null} if none found
  6.    * @throws IllegalArgumentException if {@code id} is {@literal null}
  7.    */
  8.   T findOne(ID id);
  9. /**
  10.    * Returns a reference to the entity with the given identifier.
  11.    * 
  12.    * @param id must not be {@literal null}.
  13.    * @return a reference to the entity with the given identifier.
  14.    * @see EntityManager#getReference(Class, Object)
  15.    */
  16.   T getOne(ID id);
  findOne:return 如果没有找到,则使用给定id或{@literal null}的实体。 getOne:return 对具有给定标识符的实体的引用。   好了,我们在看一下debug给出的数据 findOne:当我查询一个不存在的id数据时,返回的值是null. getOne:当我查询一个不存在的id数据时,直接抛出异常,因为它返回的是一个引用,简单点说就是一个代理对象。 所以说,如果想无论如何都有一个返回,那么就用findOne,否则使用getOne。   原文地址:https://blog.csdn.net/u012462033/article/details/79466679/  
  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0