Spring Data JPA 中 getOne、findById、findOne 的区别

1、getOne 方法(为null时会报错慎用

getOne 是一个延迟加载方法,它并不立即访问数据库,而是返回一个代理(proxy)对象,这个代理对象是对实体对象的引用,仅在 使用代理对象访问对象属性时才会去真正访问数据库 ,如果找不到,则抛出 EntityNotFoundException

源码:

public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
	/**
	 * 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);
}

2、findById 方法

findById 方法会立即(EAGER)访问数据库,并返回和指定 ID 关联的实体对象;如果没有找到,则返回 Optional.empty()

源码:

public interface CrudRepository<T, ID> extends Repository<T, ID> {	
	/**
	 * Retrieves an entity by its id.
	 *
	 * @param id must not be {@literal null}.
	 * @return the entity with the given id or {@literal Optional#empty()} if none found.
	 * @throws IllegalArgumentException if {@literal id} is {@literal null}.
	 */
	Optional<T> findById(ID id);
}

3、findOne 方法

除了 findByIdgetOne 外,Spring Data JPA 还提供了两个 findOne 方法:

  • Optional<T> findOne(@Nullable Specification<T> spec)
  • <S extends T> Optional<S> findOne(Example<S> example)

这两个方法用于需要动态构建多条件查询的场景中,它们都是立即访问数据库的。

返回类型为 Optional ,如果没有检索到,返回 Optional.empty(),结果满足条件的记录条数超过一条,则抛出 IncorrectResultSizeDataAccessException

源码:

public interface QueryByExampleExecutor<T> {
/**
	 * Returns a single entity matching the given {@link Example} or {@literal null} if none was found.
	 *
	 * @param example must not be {@literal null}.
	 * @return a single entity matching the given {@link Example} or {@link Optional#empty()} if none was found.
	 * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the Example yields more than one result.
	 */
	<S extends T> Optional<S> findOne(Example<S> example);
}
public interface JpaSpecificationExecutor<T> {
/**
	 * Returns a single entity matching the given {@link Specification} or {@link Optional#empty()} if none found.
	 *
	 * @param spec can be {@literal null}.
	 * @return never {@literal null}.
	 * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if more than one entity found.
	 */
	Optional<T> findOne(@Nullable Specification<T> spec);
}

4、findOne 使用样例

​ 4.1 findOne(@Nullable Specification<T> spec);

Optional<User> user =
        postRepository.findOne(
            (root, query, cb) ->
                cb.and(cb.equal(root.get("openId"), "aaa"), cb.equal(root.get("state"), 1)));

​ 4.2 findOne(Example<S> example);

User u = new User();
u.setOpenId("xxx");
u.setState(1);
Example<User> example = Example.of(u);
Optional<User> user = postRepository.findOne(example);

以上两种写法是等效的,执行的 SQL 如下:

Hibernate: select user0_.id as id1_0_, user0_.created_at as created_2_0_, user0_.open_id as open_id3_0_, user0_.state as state4_0_ from t_users user0_ where user0_.open_id=? and user0_.state=1

5、总结

1、getOne 是延迟加载;而 findByIdfindOne 是立即加载。

2、 getOne 如果找不到记录会抛出EntityNotFoundException;而 findByIdfindOne 会返回 Optional.empty()

3、 在 @ManyToOne 的场景中使用 findOne ,可以获得延迟加载机制带来的性能优势。

4、 在根据非 ID 查询、或动态查询的场景中,使用 findOne

5、 findOne 查询结果不能返回超过一条,否则会抛出 IncorrectResultSizeDataAccessException

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值