JPA findById方法和getOne方法有什么区别

发布时间:2021-08-14 16:31:30 作者:chen
来源:亿速云 阅读:680

这篇文章主要讲解了“JPA findById方法和getOne方法有什么区别”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“JPA findById方法和getOne方法有什么区别”吧!

目录

findById方法和getOne方法区别

Jpa基础的CRUD方法继承自接口CrudRepository<T, ID>,包含以下方法:

<S extends T> S save(S entity);
<S extends T> Iterable<S> saveAll(Iterable<S> entities);
Optional<T> findById(ID id);
boolean existsById(ID id);
Iterable<T> findAll();
Iterable<T> findAllById(Iterable<ID> ids);
long count();
void deleteById(ID id);
void delete(T entity);
void deleteAll(Iterable<? extends T> entities);
void deleteAll();

getOne()方法是JpaRepository接口中定义的

源码如下:

/**
 * Returns a reference to the entity with the given identifier. Depending on how the JPA persistence provider is
 * implemented this is very likely to always return an instance and throw an
 * {@link javax.persistence.EntityNotFoundException} on first access. Some of them will reject invalid identifiers
 * immediately.
 *
 * @param id must not be {@literal null}.
 * @return a reference to the entity with the given identifier.
 * @see EntityManager#getReference(Class, Object) for details on when an exception is thrown.
 */
T getOne(ID id);

网上找的源码:

public T getOne(ID id) {
    Assert.notNull(id, "The given id must not be null!");
    return this.em.getReference(this.getDomainClass(), id);
}

由getOne方法的源码可见,getOne方法会返回一个和给定id匹配的实体的引用,方法实际是调用getReference方法,也就是说加载策略是延迟加载,直到调用这个对象的时候才真正从数据库中进行查询(x_x)。

再看findById()方法

public Optional<T> findById(ID id) {
    Assert.notNull(id, "The given id must not be null!");
    Class<T> domainType = this.getDomainClass();
    if (this.metadata == null) {
        return Optional.ofNullable(this.em.find(domainType, id));
    } else {
        LockModeType type = this.metadata.getLockModeType();
        Map<String, Object> hints = this.getQueryHints().withFetchGraphs(this.em).asMap();
        return Optional.ofNullable(type == null ? this.em.find(domainType, id, hints) : this.em.find(domainType, id, type, hints));
    }
}

findById实际上调用的是find方法,采用立即加载方式,执行这条查询语句的时候就会立刻从数据库中进行查询,不过findById方法返回的是一个Optional,需要对这个Optional调用.get()方法才能得到需要的实体。

总结就是getOne方法是懒加载,直到调用它返回的实体时才会对数据库进行查询,findById是立即加载,主要调用方法就会去数据库查询。getOne方法直接返回一个实体,findById方法返回一个Optional,需要调用.get()方法获取实体。

spring-data-jpa中findById()的使用

springboot 2.x 版本后,较之前的版本在此方法的使用上有差:

如果找到匹配的id数据,则赋值给foo;否则则将括号中的对象赋值给foo。

Foo foo = repository.findById(id)
                    .orElse(null);
Foo foo = repository.findById(id)
                    .orElse(new Object());

感谢各位的阅读,以上就是“JPA findById方法和getOne方法有什么区别”的内容了,经过本文的学习后,相信大家对JPA findById方法和getOne方法有什么区别这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. Spring Data JPA 简单查询
  2. 一文搞懂如何在Spring Boot 正确中使用JPA

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

jpa

上一篇:Go中怎么用加密算法

下一篇:python怎么实现常用的五种排序算法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》