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,countXXBy, getXXBy後面跟屬性名稱: 具體的關鍵字,使用方法和生產成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的規範的規範,查詢方法以find | read | get 開頭,涉及查詢條件時,條件的屬性用條件關鍵字鏈接, 要注意的是:條件屬性以首字母大寫。 示例: 例如:定義一個Entity實體類: class People{ private String firstName; private String lastName; } 以上使用and條件查詢時,應這樣寫: findByLastNameAndFirstName(String lastName,String firstName); 注意:條件的屬性名稱與個數要與參數的位置與個數一一對應 2.JpaRepository查詢方法解析流程 a.Spring Data JPA框架在進行方法名解析時,會先把方法名多餘的前綴截取掉,好比find、findBy、read、readBy、get、getBy,而後對剩下部分進行解析。 b.假如建立以下的查詢:findByUserDepUuid(),框架在解析該方法時,首先剔除findBy,而後對剩下的屬性進行解析,假設查詢實體爲Doc。 -- 1.先判斷userDepUuid (根據POJO(Plain Ordinary Java Object簡單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()"。 c.特殊的參數: 還能夠直接在方法的參數上加入分頁或排序的參數,好比: 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); } d.也可使用JPA的NamedQueries,方法以下: 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,若是有,那麼就不會按照接口定義的方法來解析。 e.還可使用@Query來指定本地查詢,只要設置nativeQuery爲true,好比: @Query(value="select * from tbl_user where name like %?1" ,nativeQuery=true) public List<UserModel> findByUuidOrAge(String name); 注意:當前版本的本地查詢不支持翻頁和動態的排序 f.使用命名化參數,使用@Param便可,好比: @Query(value="select o from UserModel o where o.name like %:nn") public List<UserModel> findByUuidOrAge(@Param("nn") String name); g.一樣支持更新類的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:在調用的地方必須加事務,沒有事務不能正常執行 h.建立查詢的順序 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.多表查詢 多表查詢在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