SpringBoot JPA Data 的使用

CRUD增刪改查:

@GetMapping、@DeleteMapping、@PostMapping、@PutMapping

一、查詢

  • 在進行方法名解析時會先去掉多餘的前綴,比如find、findBy、read、readBy、get、getBy,然後對剩下部分進行解析,並且如果方法最後一個參數時 Sort 或 Pageable 類型,也會提取相關信息
  • 比如:findByNameLikeAndAgeGreaterThan
    • 剔除findBy
    • 判斷nameLikeAndAgeGreaterThan(根據POJO規範,首字母變小寫)是否爲返回對象 User 的一個屬性,如果是,則根據該屬性進行查詢,如果沒有該屬性,則進行下一步
    • 從右往左截取第一個大寫字母開頭的字符串(此處爲Than),然後檢查剩下的字符串是否爲 User 的一個屬性,如果是,則根據該屬性進行查詢,否則重複第2步,直到找出 name 爲 User 的屬性
    • 從已截取的部分後面開始,重新第 1 步開始(剔除條件語句),循環,直到把方法名處理完畢
    • 通過獲取的操作、條件和屬性、帶入參數值,生成查詢
  •  
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 findByFirstname,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)

二、刪

       DeleteBy + 上述關鍵字

三、增、改

       repository.save() 方法

       執行時:根據ID在數據庫裏查詢,若查不到該Id,則執行插入SQL。

                      若查到該Id,則執行updata操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章