# 基本查詢
基本查詢也分為兩種,一種是spring data默認已經實現,一種是根據查詢的方法來自動解析成SQL。
預先生成方法
spring data jpa 默認預先生成了一些基本的CURD的方法,例如:增、刪、改等等
## 1 繼承JpaRepository
```
public interface UserRepository extends JpaRepository<User, Long> {
}
```
## 2 使用默認方法
```
@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后面跟屬性名稱:
````
User findByUserName(String userName);
````
也使用一些加一些關鍵字And、 Or
```
User findByUserNameOrEmail(String username, String email);
```
修改、刪除、統計也是類似語法
```
Long deleteById(Long id);
Long countByUserName(String userName)
```
基本上SQL體系中的關鍵詞都可以使用,例如:LIKE、 IgnoreCase、 OrderBy。
```
List<User> findByEmailLike(String email);
User findByUserNameIgnoreCase(String userName);
List<User> findByUserNameOrderByEmailDesc(String email);
```
具體的關鍵字,使用方法和生產成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)
### 復雜查詢
在實際的開發中我們需要用到分頁、刪選、連表等查詢的時候就需要特殊的方法或者自定義SQL
分頁查詢
#### 分頁
分頁查詢在實際使用中非常普遍了,spring data jpa已經幫我們實現了分頁的功能,在查詢的方法中,需要傳入參數Pageable
,當查詢中有多個參數的時候Pageable建議做為最后一個參數傳入
```
Page<User> findALL(Pageable pageable);
Page<User> findByUserName(String userName,Pageable pageable);
```
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);
}
```
#### 排序
Sort類
導入org.springframework.data.domain.Sort;
```
Sort sort = new Sort(Sort.Direction.DESC,"mobile");
```
| 排序方式 | |
| --- | --- |
| Sort.Direction.DESC | 降序 |
| Sort.Direction.ASC | 升序 |
### 限制查詢
有時候我們只需要查詢前N個元素,或者支取前一個實體。
```
ser findFirstByOrderByLastnameAsc();
User findTopByOrderByAgeDesc();
Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);
List<User> findFirst10ByLastname(String lastname, Sort sort);
List<User> findTop10ByLastname(String lastname, Pageable pageable);
```
### 自定義SQL查詢
在SQL的查詢方法上面使用@Query注解,如涉及到刪除和修改在需要加上@Modifying.也可以根據需要添加 @Transactional 對事物的支持,查詢超時的設置等
```
@Modifying
@Query("update User u set u.userName = ?1 where c.id = ?2")
int modifyByIdAndUserId(String userName, Long id);
@Transactional
@Modifying
@Query("delete from User where id = ?1")
void deleteByUserId(Long id);
@Transactional(timeout = 10)
@Query("select u from User u where u.emailAddress = ?1")
User findByEmailAddress(String emailAddress);
```
### 多表查詢
多表查詢在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的形式來獲取
```
### 多數據源的支持
同源數據庫的多源支持
日常項目中因為使用的分布式開發模式,不同的服務有不同的數據源,常常需要在一個項目中使用多個數據源,因此需要配置sping data jpa對多數據源的使用,一般分一下為三步:
1 配置多數據源
2 不同源的實體類放入不同包路徑
3 聲明不同的包路徑下使用不同的數據源、事務支持
這里有一篇文章寫的很清楚:Spring Boot多數據源配置與使用
異構數據庫多源支持
比如我們的項目中,即需要對mysql的支持,也需要對mongodb的查詢等。
實體類聲明@Entity 關系型數據庫支持類型、聲明@Document 為mongodb支持類型,不同的數據源使用不同的實體就可以了
```
interface PersonRepository extends Repository<Person, Long> {
…
}
@Entity
public class Person {
…
}
interface UserRepository extends Repository<User, Long> {
…
}
@Document
public class User {
…
}
```
但是,如果User用戶既使用mysql也使用mongodb呢,也可以做混合使用
```
interface JpaPersonRepository extends Repository<Person, Long> {
…
}
interface MongoDBPersonRepository extends Repository<Person, Long> {
…
}
@Entity
@Document
public class Person {
…
}
```
也可以通過對不同的包路徑進行聲明,比如A包路徑下使用mysql,B包路徑下使用mongoDB
```
@EnableJpaRepositories(basePackages = "com.neo.repositories.jpa")
@EnableMongoRepositories(basePackages = "com.neo.repositories.mongo")
interface Configuration { }
```
### 其它
使用枚舉
使用枚舉的時候,我們希望數據庫中存儲的是枚舉對應的String類型,而不是枚舉的索引值,需要在屬性上面添加
```
@Enumerated(EnumType.STRING) 注解
@Enumerated(EnumType.STRING)
@Column(nullable = true)
private UserType type;
```
不需要和數據庫映射的屬性
正常情況下我們在實體類上加入注解@Entity,就會讓實體類和表相關連如果其中某個屬性我們不需要和數據庫來關聯只是在展示的時候做計算,只需要加上@Transient屬性既可。
```
@Transient
private String userName;
```