一、延迟加载和立即加载
首先我们看下源码
public T findOne(ID id) {
Assert.notNull(id, ID_MUST_NOT_BE_NULL);
Class<T> domainType = getDomainClass();
if (metadata == null) {
return em.find(domainType, id);
}
LockModeType type = metadata.getLockModeType();
Map<String, Object> hints = getQueryHints();
return type == null ? em.find(domainType, id, hints) : em.find(domainType, id, type, hints);
}
findOne()底层使用了JPA的em.find()
方法,此方法是采用立即加载
@Override
public T getOne(ID id) {
Assert.notNull(id, ID_MUST_NOT_BE_NULL);
return em.getReference(getDomainClass(), id);
}
getOne()方法采用了JPA底层的em.getReference()
方法。此方法采用延迟加载
二、返回值不同
getOne API:
- 返回对具有给定标识符的实体的引用。
- 当我查询一个不存在的id数据时,直接抛出异常,因为它返回的是一个引用,简单点说就是一个代理对象。
findOne API:
- 按ID查找实体。当我查询一个不存在的id数据时,返回的值是null.