Jpa查詢
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);
注意:條件的屬性名稱與個數要與參數的位置與個數一一對應
JpaRepository查詢方法解析流程
JPA方法名解析流程
Spring Data JPA框架在進行方法名解析時,會先把方法名多余的前綴截取掉,比如find、findBy、read、readBy、get、getBy,然后對剩下部分進行解析。
假如創建如下的查詢: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()"。
特殊的參數(分頁或排序):
-
還可以直接在方法的參數上加入分頁或排序的參數,比如:
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);
}
使用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,如果有,那么就不會按照接口定義的方法來解析。
使用@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);
創建查詢的順序
Spring Data JPA 在為接口創建代理對象時,如果發現同時存在多種上述情況可用,它該優先采用哪種策略呢?
<jpa:repositories> 提供了query-lookup-strategy 屬性,用以指定查找的順序。它有如下三個取值:
1:create-if-not-found:
如果方法通過@Query指定了查詢語句,則使用該語句實現查詢;
如果沒有,則查找是否定義了符合條件的命名查詢,如果找到,則使用該命名查詢;
如果兩者都沒有找到,則通過解析方法名字來創建查詢。
這是querylookup-strategy 屬性的默認值
2:create:通過解析方法名字來創建查詢。
即使有符合的命名查詢,或者方法通過@Query指定的查詢語句,都將會被忽略
3:use-declared-query:
如果方法通過@Query指定了查詢語句,則使用該語句實現查詢;
如果沒有,則查找是否定義了符合條件的命名查詢,如果找到,則使用該
命名查詢;如果兩者都沒有找到,則拋出異常
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);
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的形式來獲取
JPA更新
支持更新類的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:在調用的地方必須加事務,沒有事務不能正常執行
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);
注意:
執行delete和update語句一樣,需要添加@Modifying注解,使用時在Repository或者更上層需要@Transactional注解。
函數(delete)方式-刪除
-
直接可以使用delete(id),依據id來刪除一條數據
-
也可以使用deleteByName(String name)時,需要添加@Transactional注解,才能使用
-
Spring Data JPA的deleteByXXXX,是先select,在整個Transaction完了之后才執行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
* 批量解綁多個,優勢:只會形成一個SQL語句
*/
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 的區別
JpaRepository 中的save方法實現源碼:
@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方法是相當於merge+save ,它會先判斷記錄是否存在,如果存在則更新,不存在則插入記錄