SpringDataJpa:JpaRepository增刪改查操作
Jpa查詢
1. JpaRepository簡(jiǎn)單查詢
基本查詢也分為兩種,一種是spring data默認(rèn)已經(jīng)實(shí)現(xiàn),一種是根據(jù)查詢的方法來(lái)自動(dòng)解析成SQL。
預(yù)先生成方法
spring data jpa 默認(rèn)預(yù)先生成了一些基本的CURD的方法,例如:增、刪、改等等
繼承JpaRepository
public interface UserRepository extends JpaRepository<User, Long> { }
使用默認(rèn)方法
@Test public void testBaseQuery() throws Exception { User user=new User(); userRepository.findAll(); userRepository.findOne(1l); userRepository.save(user); userRepository.delete(user); userRepository.count(); userRepository.exists(1l); // ... }
自定義的簡(jiǎn)單查詢就是根據(jù)方法名來(lái)自動(dòng)生成SQL,主要的語(yǔ)法是findXXBy,readAXXBy,queryXXBy,countXXBy, getXXBy后面跟屬性名稱:
具體的關(guān)鍵字,使用方法和生產(chǎn)成SQL如下表所示
Keyword | Sample | JPQL snippet |
---|---|---|
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is,Equals | findByFirstnameIs,findByFirstnameEquals | … where x.firstname = ?1 |
Between | findByStartDateBetween | … where x.startDate between ?1 and ?2 |
LessThan | findByAgeLessThan | … where x.age < ?1 |
LessThanEqual | findByAgeLessThanEqual | … where x.age ⇐ ?1 |
GreaterThan | findByAgeGreaterThan | … where x.age > ?1 |
GreaterThanEqual | findByAgeGreaterThanEqual | … where x.age >= ?1 |
After | findByStartDateAfter | … where x.startDate > ?1 |
Before | findByStartDateBefore | … where x.startDate < ?1 |
IsNull | findByAgeIsNull | … where x.age is null |
IsNotNull,NotNull | findByAge(Is)NotNull | … where x.age not null |
Like | findByFirstnameLike | … where x.firstname like ?1 |
NotLike | findByFirstnameNotLike | … where x.firstname not like ?1 |
StartingWith | findByFirstnameStartingWith | … where x.firstname like ?1 (parameter bound with appended %) |
EndingWith | findByFirstnameEndingWith | … where x.firstname like ?1 (parameter bound with prepended %) |
Containing | findByFirstnameContaining | … where x.firstname like ?1 (parameter bound wrapped in %) |
OrderBy | findByAgeOrderByLastnameDesc | … where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | … where x.lastname <> ?1 |
In | findByAgeIn(Collection ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection age) | … where x.age not in ?1 |
TRUE | findByActiveTrue() | … where x.active = true |
FALSE | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstame) = UPPER(?1) |
按照Spring Data的規(guī)范,查詢方法以find | read | get 開頭,涉及查詢條件時(shí),條件的屬性用條件關(guān)鍵字連接,
要注意的是:條件屬性以首字母大寫。
示例:
例如:定義一個(gè)Entity實(shí)體類:
class People{ private String firstName; private String lastName; }
以上使用and條件查詢時(shí),應(yīng)這樣寫:
findByLastNameAndFirstName(String lastName,String firstName);
注意:條件的屬性名稱與個(gè)數(shù)要與參數(shù)的位置與個(gè)數(shù)一一對(duì)應(yīng)
2.JpaRepository查詢方法解析流程
JPA方法名解析流程
- Spring Data JPA框架在進(jìn)行方法名解析時(shí),會(huì)先把方法名多余的前綴截取掉
- 比如find、findBy、read、readBy、get、getBy,然后對(duì)剩下部分進(jìn)行解析。
- 假如創(chuàng)建如下的查詢:findByUserDepUuid(),框架在解析該方法時(shí),首先剔除findBy,然后對(duì)剩下的屬性進(jìn)行解析,假設(shè)查詢實(shí)體為Doc。
-- 1.先判斷userDepUuid (根據(jù)POJO(Plain Ordinary Java Object簡(jiǎn)單java對(duì)象,實(shí)際就是普通java bean)規(guī)范,首字母變?yōu)樾憽?是否是查詢實(shí)體的一個(gè)屬性,
如果根據(jù)該屬性進(jìn)行查詢;如果沒(méi)有該屬性,繼續(xù)第二步。
-- 2.從右往左截取第一個(gè)大寫字母開頭的字符串(此處為Uuid),然后檢查剩下的字符串是否為查詢實(shí)體的一個(gè)屬性,
如果是,則表示根據(jù)該屬性進(jìn)行查詢;如果沒(méi)有該屬性,則重復(fù)第二步,繼續(xù)從右往左截??;最后假設(shè) user為查詢實(shí)體的一個(gè)屬性。
-- 3.接著處理剩下部分(DepUuid),先判斷 user 所對(duì)應(yīng)的類型是否有depUuid屬性,
如果有,則表示該方法最終是根據(jù) “ Doc.user.depUuid” 的取值進(jìn)行查詢;
否則繼續(xù)按照步驟 2 的規(guī)則從右往左截取,最終表示根據(jù) “Doc.user.dep.uuid” 的值進(jìn)行查詢。
-- 4.可能會(huì)存在一種特殊情況,比如 Doc包含一個(gè) user 的屬性,也有一個(gè) userDep 屬性,此時(shí)會(huì)存在混淆。
可以明確在屬性之間加上 "_" 以顯式表達(dá)意圖,比如 "findByUser_DepUuid()" 或者 "findByUserDep_uuid()"。
特殊的參數(shù)(分頁(yè)或排序):
還可以直接在方法的參數(shù)上加入分頁(yè)或排序的參數(shù),比如:
Page<UserModel> findByName(String name, Pageable pageable); List<UserModel> findByName(String name, Sort sort);
Pageable 是spring封裝的分頁(yè)實(shí)現(xiàn)類,使用的時(shí)候需要傳入頁(yè)數(shù)、每頁(yè)條數(shù)和排序規(guī)則
@Test public void testPageQuery() throws Exception { int page=1,size=10; Sort sort = new Sort(Direction.DESC, "id"); Pageable pageable = new PageRequest(page, size, sort); userRepository.findALL(pageable); userRepository.findByUserName("testName", pageable); }
使用JPA的NamedQueries
方法如下:
1:在實(shí)體類上使用@NamedQuery,示例如下:
@NamedQuery(name = "UserModel.findByAge",query = "select o from UserModel o where o.age >= ?1")
2:在自己實(shí)現(xiàn)的DAO的Repository接口里面定義一個(gè)同名的方法,示例如下:
public List<UserModel> findByAge(int age);
3:然后就可以使用了,Spring會(huì)先找是否有同名的NamedQuery,如果有,那么就不會(huì)按照接口定義的方法來(lái)解析。
使用@Query來(lái)指定本地查詢
只要設(shè)置nativeQuery為true
比如:
@Query(value="select * from tbl_user where name like %?1" ,nativeQuery=true) public List<UserModel> findByUuidOrAge(String name);
注意:當(dāng)前版本的本地查詢不支持翻頁(yè)和動(dòng)態(tài)的排序
使用命名化參數(shù)
使用@Param即可
比如:
@Query(value="select o from UserModel o where o.name like %:nn") public List<UserModel> findByUuidOrAge(@Param("nn") String name);
創(chuàng)建查詢的順序
Spring Data JPA 在為接口創(chuàng)建代理對(duì)象時(shí),如果發(fā)現(xiàn)同時(shí)存在多種上述情況可用,它該優(yōu)先采用哪種策略呢?
<jpa:repositories> 提供了query-lookup-strategy 屬性,用以指定查找的順序。它有如下三個(gè)取值:
1:create-if-not-found:
如果方法通過(guò)@Query指定了查詢語(yǔ)句,則使用該語(yǔ)句實(shí)現(xiàn)查詢;
如果沒(méi)有,則查找是否定義了符合條件的命名查詢,如果找到,則使用該命名查詢;
如果兩者都沒(méi)有找到,則通過(guò)解析方法名字來(lái)創(chuàng)建查詢。
這是querylookup-strategy 屬性的默認(rèn)值
2:create:通過(guò)解析方法名字來(lái)創(chuàng)建查詢。
即使有符合的命名查詢,或者方法通過(guò)@Query指定的查詢語(yǔ)句,都將會(huì)被忽略
3:use-declared-query:
如果方法通過(guò)@Query指定了查詢語(yǔ)句,則使用該語(yǔ)句實(shí)現(xiàn)查詢;
如果沒(méi)有,則查找是否定義了符合條件的命名查詢,如果找到,則使用該
命名查詢;如果兩者都沒(méi)有找到,則拋出異常
3.JpaRepository限制查詢
有時(shí)候我們只需要查詢前N個(gè)元素,或者支取前一個(gè)實(shí)體。
User findFirstByOrderByLastnameAsc(); User findTopByOrderByAgeDesc(); Page<User> queryFirst10ByLastname(String lastname, Pageable pageable); List<User> findFirst10ByLastname(String lastname, Sort sort); List<User> findTop10ByLastname(String lastname, Pageable pageable);
4.JpaRepository多表查詢
多表查詢?cè)趕pring data jpa中有兩種實(shí)現(xiàn)方式,第一種是利用hibernate的級(jí)聯(lián)查詢來(lái)實(shí)現(xiàn),第二種是創(chuàng)建一個(gè)結(jié)果集的接口來(lái)接收連表查詢后的結(jié)果,這里主要第二種方式。
首先需要定義一個(gè)結(jié)果集的接口類。
public interface HotelSummary { City getCity(); String getName(); Double getAverageRating(); default Integer getAverageRatingRounded() { return getAverageRating() == null ? null : (int) Math.round(getAverageRating()); } }
查詢的方法返回類型設(shè)置為新創(chuàng)建的接口
@Query("select h.city as city, h.name as name, avg(r.rating) as averageRating " + "from Hotel h left outer join h.reviews r where h.city = ?1 group by h") Page<HotelSummary> findByCity(City city, Pageable pageable); @Query("select h.name as name, avg(r.rating) as averageRating " + "from Hotel h left outer join h.reviews r group by h") Page<HotelSummary> findByCity(Pageable pageable);
使用
Page<HotelSummary> hotels = this.hotelRepository.findByCity(new PageRequest(0, 10, Direction.ASC, "name")); for(HotelSummary summay:hotels){ System.out.println("Name" +summay.getName()); }
在運(yùn)行中Spring會(huì)給接口(HotelSummary)自動(dòng)生產(chǎn)一個(gè)代理類來(lái)接收返回的結(jié)果,代碼匯總使用getXX的形式來(lái)獲取
JPA更新
支持更新類的Query語(yǔ)句
添加@Modifying即可
比如:
@Modifying @Query(value="update UserModel o set o.name=:newName where o.name like %:nn") public int findByUuidOrAge(@Param("nn") String name,@Param("newName") String newName);
注意:
1:方法的返回值應(yīng)該是int,表示更新語(yǔ)句所影響的行數(shù)
2:在調(diào)用的地方必須加事務(wù),沒(méi)有事務(wù)不能正常執(zhí)行
JPA刪除
SQL方式-刪除
@Query(value = "delete from r_upa where user_id= ?1 and point_indecs_id in (?2)", nativeQuery = true) @Modifying void deleteByUserAndPointIndecs(Long uid, List<Long> hids);
注意:
執(zhí)行delete和update語(yǔ)句一樣,需要添加@Modifying注解,使用時(shí)在Repository或者更上層需要@Transactional注解。
函數(shù)(delete)方式-刪除
直接可以使用delete(id),依據(jù)id來(lái)刪除一條數(shù)據(jù)
也可以使用deleteByName(String name)時(shí),需要添加@Transactional注解,才能使用
Spring Data JPA的deleteByXXXX,是先select,在整個(gè)Transaction完了之后才執(zhí)行delete
JpaRepository
@NoRepositoryBean public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> { /** * Deletes the given entities in a batch which means it will create a single {@link Query}. Assume that we will clear * the {@link javax.persistence.EntityManager} after the call. * * @param entities * 批量解綁多個(gè),優(yōu)勢(shì):只會(huì)形成一個(gè)SQL語(yǔ)句 */ void deleteInBatch(Iterable<T> entities); /** * Deletes all entities in a batch call. */ void deleteAllInBatch(); }
CrudRepository
@NoRepositoryBean public interface CrudRepository<T, ID> extends Repository<T, ID> { /** * Deletes the entity with the given id. * * @param id must not be {@literal null}. * @throws IllegalArgumentException in case the given {@code id} is {@literal null} */ void deleteById(ID id); /** * Deletes a given entity. * * @param entity * @throws IllegalArgumentException in case the given entity is {@literal null}. */ void delete(T entity); /** * Deletes the given entities. * * @param entities * @throws IllegalArgumentException in case the given {@link Iterable} is {@literal null}. */ void deleteAll(Iterable<? extends T> entities); /** * Deletes all entities managed by the repository. */ void deleteAll(); }
JPA添加
利用JpaRepository和CrudRepository中的 save操作
JpaRepository
@NoRepositoryBean public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> { /* * (non-Javadoc) * @see org.springframework.data.repository.CrudRepository#save(java.lang.Iterable) */ <S extends T> List<S> saveAll(Iterable<S> entities); /** * Flushes all pending changes to the database. */ void flush(); /** * Saves an entity and flushes changes instantly. * * @param entity * @return the saved entity */ <S extends T> S saveAndFlush(S entity); }
CrudRepository
@NoRepositoryBean public interface CrudRepository<T, ID> extends Repository<T, ID> { /** * Saves a given entity. Use the returned instance for further operations as the save operation might have changed the * entity instance completely. * * @param entity must not be {@literal null}. * @return the saved entity will never be {@literal null}. */ <S extends T> S save(S entity); /** * Saves all given entities. * * @param entities must not be {@literal null}. * @return the saved entities will never be {@literal null}. * @throws IllegalArgumentException in case the given entity is {@literal null}. */ <S extends T> Iterable<S> saveAll(Iterable<S> entities); }
JpaRepository和CrudRepository 的區(qū)別
JpaRepository 中的save方法實(shí)現(xiàn)源碼:
@Transactional public <S extends T> List<S> save(Iterable<S> entities) { List<S> result = new ArrayList<S>(); if (entities == null) { return result; } for (S entity : entities) { result.add(save(entity)); } return result; }
CrudRepository 中的save方法源代碼
@Transactional public <S extends T> S save(S entity) { if (entityInformation.isNew(entity)) { em.persist(entity);//是新的就插入 return entity; } else { return em.merge(entity); //不是新的merge } }
由源碼可知CrudRepository 中的save方法是相當(dāng)于merge+save ,它會(huì)先判斷記錄是否存在,如果存在則更新,不存在則插入記錄
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java application maven項(xiàng)目打自定義zip包實(shí)例(推薦)
下面小編就為大家?guī)?lái)一篇java application maven項(xiàng)目打自定義zip包實(shí)例(推薦)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05Java數(shù)據(jù)結(jié)構(gòu)之對(duì)象比較詳解
這篇文章主要為大家詳細(xì)介紹了Java中對(duì)象的比較、集合框架中PriorityQueue的比較方式以及PriorityQueue的模擬實(shí)現(xiàn),感興趣的可以了解一下2022-07-07java開發(fā)建造者模式驗(yàn)證實(shí)例詳解
這篇文章主要為大家介紹了java開發(fā)中建造者模式的驗(yàn)證實(shí)例詳解,文中附含詳細(xì)示例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10Java 17 隨機(jī)數(shù)生成器來(lái)了一波穩(wěn)穩(wěn)的增強(qiáng)
JDK 當(dāng)中的隨機(jī)數(shù)生成器其實(shí)對(duì)于普通開發(fā)者來(lái)講基本夠用,不過(guò)對(duì)于一些比較復(fù)雜的場(chǎng)景來(lái)講,原有的類結(jié)構(gòu)對(duì)擴(kuò)展并不是很友好,除了 Random 類,JDK 當(dāng)中還提供了另外幾個(gè)隨機(jī)數(shù)的成員,下面文章將詳細(xì)介紹,需要的朋友可以參考一下2021-09-09