首页 > 编程语言 > 详细

Spring Data Jpa中getOne和FindOne的区别

时间:2021-06-29 23:12:20      阅读:24      评论:0      收藏:0      [点我收藏+]

在使用 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

Spring Data Jpa中getOne和FindOne的区别

原文:https://www.cnblogs.com/hnxbp/p/14950719.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!