zoukankan      html  css  js  c++  java
  • Spring Data Jpa中getOne和FindOne的区别

    在使用 SpringDataJPA 过程中,但是发现它和Hibernate有很多相似之处,比如这个根据主键获取某条数据的函数:findOne() 和 getOne(),就很像Hibernate中的load和get. 之前没有特别注意这两个获取单条数据的方法,所以找了一个带One的就用,结果有时候测试发现 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:return 如果没有找到,则使用给定id或{@literal null}的实体。

    getOne:return 对具有给定标识符的实体的引用。

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

    所以说,如果想无论如何都有一个返回,那么就用findOne,否则使用getOne

  • 相关阅读:
    Bugku web web基础$_GET
    Bugku web 计算器
    Bugku web web2
    Bugku 杂项 宽带信息泄露
    Bugku 杂项 猜
    Bugku 杂项 又一张图片,还单纯吗
    Bugku 杂项 啊哒
    Bugku 杂项 眼见非实(ISCCCTF)
    Bugku 杂项 telnet
    Bugku 杂项 隐写
  • 原文地址:https://www.cnblogs.com/hnxbp/p/14950719.html
Copyright © 2011-2022 走看看