1. 程式人生 > >SpringDataJpa:JpaRepository增刪改查

SpringDataJpa:JpaRepository增刪改查

1. JpaRepository簡單查詢

基本查詢也分為兩種,一種是spring data預設已經實現,一種是根據查詢的方法來自動解析成SQL。

  • 預先生成方法

spring data jpa 預設預先生成了一些基本的CURD的方法,例如:增、刪、改等等

繼承JpaRepository

public interface UserRepository extends JpaRepository<User, Long> {
}
  • 使用預設方法

@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);
    // ...
}
  • 自定義的簡單查詢就是根據方法名來自動生成SQL,主要的語法是findXXBy,readAXXBy,queryXXBy,countXXBygetXXBy後面跟屬性名稱:
  • 具體的關鍵字,使用方法和生產成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)

按照SpringData的規範,查詢方法以find | read | get 開頭,涉及查詢條件時,條件的屬性條件關鍵字連線,

要注意的是條件屬性以首字母大寫

  • 示例:

例如:定義一個Entity實體類:

class People{
       private String firstName;
       private String lastName;
}

以上使用and條件查詢時,應這樣寫:

findByLastNameAndFirstName(String lastName,String firstName);

注意:條件的屬性名稱與個數要與引數的位置與個數一一對應

2.JpaRepository查詢方法解析流程

JPA方法名解析流程

  • SpringData JPA框架在進行方法名解析時,會先把方法名多餘的字首擷取掉
  • 比如findfindByreadreadBygetgetBy,然後對剩下部分進行解析。
  • 假如建立如下的查詢:findByUserDepUuid(),框架在解析該方法時,首先剔除findBy,然後對剩下的屬性進行解析,假設查詢實體為Doc

-- 1.先判斷userDepUuid (根據POJOPlainOrdinaryJavaObject簡單java物件,實際就是普通java bean)規範,首字母變為小寫。)是否是查詢實體的一個屬性

如果根據該屬性進行查詢;如果沒有該屬性,繼續第二步。

-- 2.從右往左擷取第一個大寫字母開頭的字串(此處為Uuid),然後檢查剩下的字串是否為查詢實體的一個屬性

如果是,則表示根據該屬性進行查詢;如果沒有該屬性,則重複第二步,繼續從右往左擷取;最後假設 user為查詢實體的一個屬性。

-- 3.接著處理剩下部分DepUuid),先判斷 user 所對應的型別是否有depUuid屬性,

如果有,則表示該方法最終是根據Doc.user.depUuid的取值進行查詢;

否則繼續按照步驟2的規則從右往左擷取,最終表示根據Doc.user.dep.uuid的值進行查詢。

-- 4.可能會存在一種特殊情況,比如Doc包含一個 user 的屬性,也有一個 userDep 屬性,此時會存在混淆。

可以明確在屬性之間加上"_"以顯式表達意圖,比如"findByUser_DepUuid()"或者"findByUserDep_uuid()"


特殊的引數(分頁或排序):

  • 還可以直接在方法的引數上加入分頁或排序的引數,比如:
Page<UserModel> findByName(String name, Pageable pageable);
List<UserModel> findByName(String name, Sort sort);
  • Pageable 是spring封裝的分頁實現類,使用的時候需要傳入頁數、每頁條數和排序規則
@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);
}

使用JPANamedQueries

  • 方法如下:

1:在實體類上使用@NamedQuery,示例如下:

@NamedQuery(name = "UserModel.findByAge",query = "select o from UserModel o where o.age >= ?1")

2:在自己實現的DAO的Repository接口裡面定義一個同名的方法,示例如下:

public List<UserModel> findByAge(int age);

3:然後就可以使用了,Spring會先找是否有同名的NamedQuery,如果有,那麼就不會按照介面定義的方法來解析。

使用@Query來指定本地查詢

只要設定nativeQuery為true

  • 比如:
@Query(value="select * from tbl_user where name like %?1" ,nativeQuery=true)
public List<UserModel> findByUuidOrAge(String name);

注意:當前版本的本地查詢不支援翻頁和動態的排序

使用命名化引數

使用@Param即可

比如:

@Query(value="select o from UserModel o where o.name like %:nn")
public List<UserModel> findByUuidOrAge(@Param("nn") String name);

支援更新類的Query語句

新增@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:方法的返回值應該是int,表示更新語句所影響的行數

2:在呼叫的地方必須加事務,沒有事務不能正常執行

建立查詢的順序

  • Spring Data JPA 在為介面建立代理物件時,如果發現同時存在多種上述情況可用,它該優先採用哪種策略呢?

<jpa:repositories> 提供了query-lookup-strategy 屬性,用以指定查詢的順序。它有如下三個取值:

1:create-if-not-found:

如果方法通過@Query指定了查詢語句,則使用該語句實現查詢;

如果沒有,則查詢是否定義了符合條件的命名查詢,如果找到,則使用該命名查詢;

如果兩者都沒有找到,則通過解析方法名字來建立查詢。

這是querylookup-strategy 屬性的預設值

2:create:通過解析方法名字來建立查詢。

即使有符合的命名查詢,或者方法通過@Query指定的查詢語句,都將會被忽略

3:use-declared-query:

如果方法通過@Query指定了查詢語句,則使用該語句實現查詢;

如果沒有,則查詢是否定義了符合條件的命名查詢,如果找到,則使用該

命名查詢;如果兩者都沒有找到,則丟擲異常

3.JpaRepository限制查詢

  • 有時候我們只需要查詢前N個元素,或者支取前一個實體。
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多表查詢

  • 多表查詢在spring data jpa中有兩種實現方式,第一種是利用hibernate的級聯查詢來實現,第二種是建立一個結果集的介面來接收連表查詢後的結果,這裡主要第二種方式。
  • 首先需要定義一個結果集的介面類
public interface HotelSummary {
    City getCity();
    String getName();
    Double getAverageRating();
    default Integer getAverageRatingRounded() {
        return getAverageRating() == null ? null : (int) Math.round(getAverageRating());
    }
}
  • 查詢的方法返回型別設定為新建立的介面
@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());
    }

在執行中Spring會給介面(HotelSummary)自動生產一個代理類來接收返回的結果,程式碼彙總使用getXX的形式來獲取

參考來源:http://www.ityouknow.com/springboot/2016/08/20/springboot(%E4%BA%94)-spring-data-jpa%E7%9A%84%E4%BD%BF%E7%94%A8.html