1. 程式人生 > >Spring Boot JPA使用詳解

Spring Boot JPA使用詳解

spring data jpa介紹

首先了解JPA是什麼?

JPA(Java Persistence API)是Sun官方提出的Java持久化規範。它為Java開發人員提供了一種物件/關聯對映工具來管理Java應用中的關係資料。他的出現主要是為了簡化現有的持久化開發工作和整合ORM技術,結束現在Hibernate,TopLink,JDO等ORM框架各自為營的局面。值得注意的是,JPA是在充分吸收了現有Hibernate,TopLink,JDO等ORM框架的基礎上發展而來的,具有易於使用,伸縮性強等優點。從目前的開發社群的反應上看,JPA受到了極大的支援和讚揚,其中就包括了Spring與EJB3.0的開發團隊。

注意:JPA是一套規範,不是一套產品,那麼像Hibernate,TopLink,JDO他們是一套產品,如果說這些產品實現了這個JPA規範,那麼我們就可以叫他們為JPA的實現產品。

spring data jpa

Spring Data JPA 是 Spring 基於 ORM 框架、JPA 規範的基礎上封裝的一套JPA應用框架,可使開發者用極簡的程式碼即可實現對資料的訪問和操作。它提供了包括增刪改查等在內的常用功能,且易於擴充套件!學習並使用 Spring Data JPA 可以極大提高開發效率!

spring data jpa讓我們解脫了DAO層的操作,基本上所有CRUD都可以依賴於它來實現

基本查詢

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

預先生成方法

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

1 繼承JpaRepository

public interface UserRepository extends JpaRepository<User, Long> {
}

2 使用預設方法

@Test
publicvoidtestBaseQuery() 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後面跟屬性名稱:

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
publicvoidtestPageQuery() 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);
}

限制查詢

有時候我們只需要查詢前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查詢

其實Spring data 覺大部分的SQL都可以根據方法名定義的方式來實現,但是由於某些原因我們想使用自定義的SQL來查詢,spring data也是完美支援的;在SQL的查詢方法上面使用@Query註解,如涉及到刪除和修改在需要加上@Modifying.也可以根據需要新增 @Transactional 對事物的支援,查詢超時的設定等

@Modifying
@Query("update User u set u.userName = ?1 where c.id = ?2")
intmodifyByIdAndUserId(String  userName, Long id);
    
@Transactional
@Modifying
@Query("delete from User where id = ?1")
voiddeleteByUserId(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 宣告不同的包路徑下使用不同的資料來源、事務支援

異構資料庫多源支援

比如我們的專案中,即需要對mysql的支援,也需要對mongodb的查詢等。

實體類宣告@Entity 關係型資料庫支援型別、宣告@Document 為mongodb支援型別,不同的資料來源使用不同的實體就可以了

interface PersonRepository extends Repository<Person, 
            
           

相關推薦

純幹貨,Spring-data-jpa(轉)

數據庫表結構 attribute 類型 n+1 asq sep pointcut 如何 odin 本篇進行Spring-data-jpa的介紹,幾乎涵蓋該框架的所有方面,在日常的開發當中,基本上能滿足所有需求。這裏不講解JPA和Spring-data-jpa單獨使用,所有的

SpringBoot進擊 | 二淺出:Spring Boot配置

1.前言 上一節:SpringBoot進擊 | 一淺出:Spring Boot簡單快速上手書 上一篇介紹了 Spring Boot 的入門,在一般情況下,我們不需要做太多的配置就能夠讓 Spring Boot 正常執行。因為其使用“習慣優於配置”(專案中存在大量的配置,此外還內建了一

Spring-data-jpa

本篇進行Spring-data-jpa的介紹,幾乎涵蓋該框架的所有方面,在日常的開發當中,基本上能滿足所有需求。這裡不講解JPA和Spring-data-jpa單獨使用,所有的內容都是在和Spring整合的環境中實現。如果需要了解該框架的入門,百度一下,很多入門的介紹。在這篇文章的接下來一篇,會有一

Spring Boot Actuator與深入應用(一):Actuator 1.x

《Spring Boot Actuator詳解與深入應用》預計包括三篇,第一篇重點講Spring Boot Actuator 1.x的應用與定製端點;第二篇將會對比Spring Boot Actuator 2.x 與1.x的區別,以及應用和定製2.x的端點;第三篇將會介紹Actuator metric指

Spring Boot Actuator與深入應用(二):Actuator 2.x

《Spring Boot Actuator詳解與深入應用》預計包括三篇,第一篇重點講Spring Boot Actuator 1.x的應用與定製端點;第二篇將會對比Spring Boot Actuator 2.x 與1.x的區別,以及應用和定製2.x的端點;第三篇將會介紹Actuator metric指

Spring Boot Admin Spring Boot 2.0,基於 Eureka 的實現)

Spring Boot Admin 用於監控基於 Spring Boot 的應用,它是在 Spring Boot Actuator 的基礎上提供簡潔的視覺化 WEB UI。 (一)簡介 Spring Boot Admin 提供了很多功能,如顯示 name、id 和 version,顯示線上狀態,

第13章 Spring Boot Security

spring-boot-starter-security是對Spring Security的一個封裝,具體如下 <dependency> <groupId>org.springframework.boot</groupId>

Spring Boot Actuator與深入應用(三):Prometheus+Grafana應用監控

《Spring Boot Actuator詳解與深入應用》預計包括三篇,第一篇重點講Spring Boot Actuator 1.x的應用與定製端點;第二篇將會對比Spring Boot Actuator 2.x 與1.x的區別,以及應用和定製2.x的端點;第三篇將會介紹Actuator metric指

spring data jpa

本篇進行Spring-data-jpa的介紹,幾乎涵蓋該框架的所有方面,在日常的開發當中,基本上能滿足所有需求。這裡不講解JPA和Spring-data-jpa單獨使用,所有的內容都是在和Spring整合的環境中實現。如果需要了解該框架的入門,百度一下,很多入門的介紹。在這篇

Spring-data-jpa

本篇進行Spring-data-jpa的介紹,幾乎涵蓋該框架的所有方面,在日常的開發當中,基本上能滿足所有需求。這裡不講解JPA和Spring-data-jpa單獨使用,所有的內容都是在和Spring整合的環境中實現。如果需要了解該框架的入門,百度一下,很多入門的介紹。在這篇

SpringBoot之(一)Spring Boot配置

  一、@Value賦值 當我們建立一個springboot專案的時候,系統預設會為我們在src/main/java/resources目錄下建立一個application.properties。個人習慣,我會將application.properties改為application

Spring Boot 日誌

日誌 如果看Spring boot 日誌,直接跳到 3 1、日誌框架 案例: 小張;開發一個大型系統; ​ 1、System.out.println(“”);將關鍵資料列印在控制檯;去掉?寫在一個檔案? ​ 2、框架來記錄系統的一些執行時

Spring Boot 入門

原始碼分析: J2EE的整體整合解決方案和自動配置都在spring-boot-autoconfigure-X.X.X.RELEASE.jar中:

Spring Boot深入

Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Boot致力於在蓬勃發展的快速應用開發領域(rapid a

純乾貨,Spring-data-jpa,全方位介紹。

轉載地址:http://www.cnblogs.com/dreamroute/p/5173896.html 本篇進行Spring-data-jpa的介紹,幾乎涵蓋該框架的所有方面,在日常的開發當中,基本上能滿足所有需求。這裡不講解JPA和Spring-data-

spring-boot 註解

一、註解(annotations)列表  @SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration註解。其中@ComponentScan讓spring Boot掃描到C

Spring Boot Security

lur min ear 受保護 main servle 重寫 tro bstr 簡介 Spring Security,這是一種基於 Spring AOP 和 Servlet 過濾器的安全框架。它提供全面的安全性解決方案,同時在 Web 請求級和方法調用級處理身份確認和授權。

Spring Boot (九): 微服務應用監控 Spring Boot Actuator

1. 引言 在當前的微服務架構方式下,我們會有很多的服務部署在不同的機器上,相互是通過服務呼叫的方式進行互動,一個完整的業務流程中間會經過很多個微服務的處理和傳遞,那麼,如何能知道每個服務的健康狀況就顯得尤為重要。 萬幸的是 Spring Boot 為我們提供了監控模組 Spring Boot Actua

spring boot中使用JPA

1.首先在pom.xml檔案中匯入jar包 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <g

Spring Boot JPA使用

spring data jpa介紹 首先了解JPA是什麼? JPA(Java Persistence API)是Sun官方提出的Java持久化規範。它為Java開發人員提供了一種物件/關聯對映工具來管理Java應用中的關係資料。他的出現主要是為了簡化現有的持久化開發工