1. 程式人生 > 實用技巧 >spring-data-jpa中的查詢方法

spring-data-jpa中的查詢方法

查詢方法,就是根據方法名來檢索資料。按照一定的規則,通過方法名描述要檢索的欄位,過濾的條件,排序的策略等等,它們大都以find, get... 等開頭。spring-data-jpa會自動解析,並且完成檢索。省時省力。

在 Repository 中定義查詢方法

public interface UserRepository extends Repository<User, Long> {
  // 根據emailAddress和lastname 檢索所有的記錄
  List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);
}

這個方法最終執行的JPQL

select u from User u where u.emailAddress = ?1 and u.lastname = ?2

支援的語法

關鍵字 例如 最終執行的JPQL 片段
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
IsEquals 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
IsNullNull findByAge(Is)Null … where x.age is null
IsNotNullNotNull 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<Age> ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection<Age> ages) … 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)

使用到InNotIn等對集合進行計算關鍵的字方法,支援使用Collection子類,或者陣列作為引數的形參。

支援物件屬性導航

class User {
    // User物件關聯了一個Address 物件
	Address address;
}
class Address {
	String name;
}
public interface UserRepositroy extends JpaRepository<User, Integer>{
    // 從address屬性導航到它的name屬性
	findByAddressName(String name); 

    // 更為科學的寫法, 通過下戶線標識遍歷的節點
	findByAddress_Name(String name); 
}

JPA裡面, 下戶線是保留識別符號,但是下劃線又破話了Java的駝峰規則

分頁和排序

只需要在方法的最後一個引數定義: Sort / Pageable 物件,即可自動的完成排序/分頁

SortPageable是JPA定義用來排序和分頁的物件

也可以通過 First/Top 方法名限制結果集

findFirst10ByName(String name);
findTop10ByName(String name);

以上2個方法,都表示根據 name 屬性檢索前10條記錄

官方文件

這個花樣確實多,不過用到的就那麼幾個,有興趣,可以閱讀官方文件系統學習
https://docs.spring.io/spring-data/jpa/docs/current-SNAPSHOT/reference/html/#jpa.query-methods

原文:https://springboot.io/t/topic/2208