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

  • 相关阅读:
    HDU6655 Just Repeat(2019杭电多校J题)
    贪吃蛇-
    2D命令行小游戏Beta1.0
    寒假作业三
    星 辰 · 第 一 条 约 定
    塔 · 第 三 条 约 定
    class中的东西和继承、多态的概念
    塔 · 第 一 条 约 定
    部门学习总结之类的
    作业二
  • 原文地址:https://www.cnblogs.com/hnxbp/p/14950719.html
Copyright © 2011-2022 走看看