欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Data JPA中findOne()和getOne()用法

 更新時間:2023年11月30日 15:08:41   作者:閆二白  
這篇文章主要介紹了Spring Data JPA中findOne()和getOne()的用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

引言

最近在使用SpringDataJPA做CRUD功能,在做到需要查詢單個的功能的時候,

我們發(fā)現(xiàn)SpringDataJPA為我們提供了兩種辦法findOne() 和 getOne(),

那我們該如何選擇呢,他們之間的區(qū)別又是什么呢,下面我們來總結(jié)一下。

findOne() 和 getOne()的區(qū)別

首先我們看一下Spring官方對他們的解釋

/**   
 *    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:當我查詢一個不存在的id數(shù)據(jù)時,返回的值是null.


在這里插入圖片描述
 

getOne: return 對具有給定標識符的實體的引用。

當我查詢一個不存在的id數(shù)據(jù)時,直接拋出異常,因為它返回的是一個引用,簡單點說就是一個代理對象。


在這里插入圖片描述

我們知道SpringDataJPA底層默認使用Hibernate,hibernate對于load方法認為該數(shù)據(jù)在數(shù)據(jù)庫中一定存在,可以放心的使用代理來延遲加載,如果在使用過程中發(fā)現(xiàn)了問題,只能拋異常;

而對于get方法,hibernate一定要獲取到真實的數(shù)據(jù),否則返回null。

所以我們可以吧findOne() 當成hibernate中g(shù)et方法,getOne()當成hibernate中l(wèi)oad方法來記憶。。。。。

補充

以前我們使用Spring Data Jpa 的查詢單個的時候,可以使用findOne()方法根據(jù)id查詢。

但是在2.0.5以后,不能用來當作根據(jù)id查詢了。2.0.5以后變成了findById(id).get()來查詢了。

2.0.5版本以前的CrudRepository類是這樣的:

@NoRepositoryBean
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
    <S extends T> S save(S var1);

    <S extends T> Iterable<S> save(Iterable<S> var1);

    T findOne(ID var1);

    boolean exists(ID var1);

    Iterable<T> findAll();

    Iterable<T> findAll(Iterable<ID> var1);

    long count();

    void delete(ID var1);

    void delete(T var1);

    void delete(Iterable<? extends T> var1);

    void deleteAll();
}

2.0.5版本以后的CrudRepository類是這樣的:

@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {
    <S extends T> S save(S var1);

    <S extends T> Iterable<S> saveAll(Iterable<S> var1);

    Optional<T> findById(ID var1);

    boolean existsById(ID var1);

    Iterable<T> findAll();

    Iterable<T> findAllById(Iterable<ID> var1);

    long count();

    void deleteById(ID var1);

    void delete(T var1);

    void deleteAll(Iterable<? extends T> var1);

    void deleteAll();
}

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論