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)文章
解決httpServletRequest.getParameter獲取不到參數(shù)的問題
這篇文章主要介紹了解決httpServletRequest.getParameter獲取不到參數(shù)的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07Spring Boot 工程的創(chuàng)建和運行(圖文)
這篇文章主要介紹了Spring Boot 工程的創(chuàng)建和運行(圖文),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02Spring Data JPA 如何使用QueryDsl查詢并分頁
這篇文章主要介紹了Spring Data JPA 如何使用QueryDsl查詢并分頁,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11