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

  • 相关阅读:
    Python3之redis使用
    python3中urllib的基本使用
    最安全的api接口认证
    Python—I/O多路复用
    Python—RabbitMQ
    Python—sqlalchemy
    python操作MongoDB
    Python—进程、线程、协程
    推断client手机类型,并跳转到对应的app下载页面
    ExtJs--13-- Ext.apply(src,apply) 和 Ext.applyIf(src,apply) 两个方法的使用和差别比較
  • 原文地址:https://www.cnblogs.com/hnxbp/p/14950719.html
Copyright © 2011-2022 走看看