SpringDataJpa:JpaRepository增刪改查操作
Jpa查詢
1. JpaRepository簡單查詢
基本查詢也分為兩種,一種是spring data默認已經實現(xiàn),一種是根據(jù)查詢的方法來自動解析成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);
// ...
}
自定義的簡單查詢就是根據(jù)方法名來自動生成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的規(guī)范,查詢方法以find | read | get 開頭,涉及查詢條件時,條件的屬性用條件關鍵字連接,
要注意的是:條件屬性以首字母大寫。
示例:
例如:定義一個Entity實體類:
class People{
private String firstName;
private String lastName;
}
以上使用and條件查詢時,應這樣寫:
findByLastNameAndFirstName(String lastName,String firstName);
注意:條件的屬性名稱與個數(shù)要與參數(shù)的位置與個數(shù)一一對應
2.JpaRepository查詢方法解析流程
JPA方法名解析流程
- Spring Data JPA框架在進行方法名解析時,會先把方法名多余的前綴截取掉
- 比如find、findBy、read、readBy、get、getBy,然后對剩下部分進行解析。
- 假如創(chuàng)建如下的查詢:findByUserDepUuid(),框架在解析該方法時,首先剔除findBy,然后對剩下的屬性進行解析,假設查詢實體為Doc。
-- 1.先判斷userDepUuid (根據(jù)POJO(Plain Ordinary Java Object簡單java對象,實際就是普通java bean)規(guī)范,首字母變?yōu)樾憽?是否是查詢實體的一個屬性,
如果根據(jù)該屬性進行查詢;如果沒有該屬性,繼續(xù)第二步。
-- 2.從右往左截取第一個大寫字母開頭的字符串(此處為Uuid),然后檢查剩下的字符串是否為查詢實體的一個屬性,
如果是,則表示根據(jù)該屬性進行查詢;如果沒有該屬性,則重復第二步,繼續(xù)從右往左截?。蛔詈蠹僭O user為查詢實體的一個屬性。
-- 3.接著處理剩下部分(DepUuid),先判斷 user 所對應的類型是否有depUuid屬性,
如果有,則表示該方法最終是根據(jù) “ Doc.user.depUuid” 的取值進行查詢;
否則繼續(xù)按照步驟 2 的規(guī)則從右往左截取,最終表示根據(jù) “Doc.user.dep.uuid” 的值進行查詢。
-- 4.可能會存在一種特殊情況,比如 Doc包含一個 user 的屬性,也有一個 userDep 屬性,此時會存在混淆。
可以明確在屬性之間加上 "_" 以顯式表達意圖,比如 "findByUser_DepUuid()" 或者 "findByUserDep_uuid()"。
特殊的參數(shù)(分頁或排序):
還可以直接在方法的參數(shù)上加入分頁或排序的參數(shù),比如:
Page<UserModel> findByName(String name, Pageable pageable); List<UserModel> findByName(String name, Sort sort);
Pageable 是spring封裝的分頁實現(xiàn)類,使用的時候需要傳入頁數(shù)、每頁條數(shù)和排序規(guī)則
@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:在自己實現(xiàn)的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);
注意:當前版本的本地查詢不支持翻頁和動態(tài)的排序
使用命名化參數(shù)
使用@Param即可
比如:
@Query(value="select o from UserModel o where o.name like %:nn")
public List<UserModel> findByUuidOrAge(@Param("nn") String name);
創(chuàng)建查詢的順序
Spring Data JPA 在為接口創(chuàng)建代理對象時,如果發(fā)現(xiàn)同時存在多種上述情況可用,它該優(yōu)先采用哪種策略呢?
<jpa:repositories> 提供了query-lookup-strategy 屬性,用以指定查找的順序。它有如下三個取值:
1:create-if-not-found:
如果方法通過@Query指定了查詢語句,則使用該語句實現(xiàn)查詢;
如果沒有,則查找是否定義了符合條件的命名查詢,如果找到,則使用該命名查詢;
如果兩者都沒有找到,則通過解析方法名字來創(chuàng)建查詢。
這是querylookup-strategy 屬性的默認值
2:create:通過解析方法名字來創(chuàng)建查詢。
即使有符合的命名查詢,或者方法通過@Query指定的查詢語句,都將會被忽略
3:use-declared-query:
如果方法通過@Query指定了查詢語句,則使用該語句實現(xiàn)查詢;
如果沒有,則查找是否定義了符合條件的命名查詢,如果找到,則使用該
命名查詢;如果兩者都沒有找到,則拋出異常
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中有兩種實現(xiàn)方式,第一種是利用hibernate的級聯(lián)查詢來實現(xiàn),第二種是創(chuàng)建一個結果集的接口來接收連表查詢后的結果,這里主要第二種方式。
首先需要定義一個結果集的接口類。
public interface HotelSummary {
City getCity();
String getName();
Double getAverageRating();
default Integer getAverageRatingRounded() {
return getAverageRating() == null ? null : (int) Math.round(getAverageRating());
}
}
查詢的方法返回類型設置為新創(chuàng)建的接口
@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,表示更新語句所影響的行數(shù)
2:在調用的地方必須加事務,沒有事務不能正常執(zhí)行
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);
注意:
執(zhí)行delete和update語句一樣,需要添加@Modifying注解,使用時在Repository或者更上層需要@Transactional注解。
函數(shù)(delete)方式-刪除
直接可以使用delete(id),依據(jù)id來刪除一條數(shù)據(jù)
也可以使用deleteByName(String name)時,需要添加@Transactional注解,才能使用
Spring Data JPA的deleteByXXXX,是先select,在整個Transaction完了之后才執(zhí)行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
* 批量解綁多個,優(yōu)勢:只會形成一個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 的區(qū)別
JpaRepository 中的save方法實現(xiàn)源碼:
@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 ,它會先判斷記錄是否存在,如果存在則更新,不存在則插入記錄
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
intellij idea快速查看當前類中的所有方法(推薦)
這篇文章主要介紹了intellij idea快速查看當前類中的所有方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
SpringBoot使用CXF集成WebService的方法
這篇文章主要介紹了SpringBoot使用CXF集成WebService的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08
jackson在springboot中的使用方式-自定義參數(shù)轉換器
這篇文章主要介紹了jackson在springboot中的使用方式-自定義參數(shù)轉換器,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
Java中Stream實現(xiàn)List排序的六個核心技巧總結
這篇文章主要介紹了Java中Stream實現(xiàn)List排序的六個核心技巧,分別是自然序排序、反向排序、空值安全處理、多字段組合排序、并行流加速、原地排序等,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2025-04-04
Java連接MYSQL數(shù)據(jù)庫的實現(xiàn)步驟
以下的文章主要描述的是java連接MYSQL數(shù)據(jù)庫的正確操作步驟,在此篇文章里我們主要是以實例列舉的方式來引出其具體介紹2013-06-06
Spring MVC結合Spring Data JPA實現(xiàn)按條件查詢和分頁
這篇文章主要為大家詳細介紹了Spring MVC結合Spring Data JPA實現(xiàn)按條件查詢,以及分頁效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
詳解如何在SpringBoot中優(yōu)雅地重試調用第三方API
作為后端程序員,我們的日常工作就是調用一些第三方服務,將數(shù)據(jù)存入數(shù)據(jù)庫,返回信息給前端。本文為大家介紹了如何在SpringBoot中優(yōu)雅地重試調用第三方API,需要的可以參考一下2022-12-12
簡單的理解java集合中的HashSet和HashTree幾個重寫方法
這篇文章主要介紹了簡單的理解java集合中的HashSet和HashTree幾個重寫方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10

