1. 程式人生 > >《深入理解Spring Cloud與微服務構建》學習筆記(五)~SpringBoot 整合 JPA

《深入理解Spring Cloud與微服務構建》學習筆記(五)~SpringBoot 整合 JPA

JPA是一個數據持久化的類和方法的集合,目前java專案開發中提到的JPA一般是指用Hibernate的實現,因為在java的ORM框架中,只有Hibernate實現的最好。當前學習在SpringBoot專案中使用JPA,資料庫使用mysql。

一、新建一個SpringBoot專案,在pom.xml中引入jpa的依賴,和mysql資料庫聯結器的依賴:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

也可以在建立專案的時候選擇模組,此處會自動加入依賴,如: 二、配置資料來源,在application.yml中進行配置,基礎的配置都比較容易看懂,除了url、username、password需要調整,其他都是不用改的。

debug: false
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jpatest
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true

三、建立實體物件:通過@Entity註解表明該類是一個實體類,它和資料庫表明是對應的。@Id註解表明該變數對應資料庫的id,@GeneratedValue註解配置id欄位為自增長,@Column註解表明該變數對應資料庫表中的欄位。還有很多註解屬性,後面用到了可以進行實踐。


@Entity
public class JpaUser {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id ;

    @Column
    private String username ;

    @Column
    private String password ;

    //略過get、set
}

此時啟動服務,會看到控制檯會有生成表的sql,如: 再看資料庫,也生成了對應的表,說明我們第一步成功了,如: 四、建立DAO層    建立一個DAO類,繼承JpaRepository介面,繼承之後就能對資料庫進行讀寫操作,包含基本的單表查詢方法,。在 Dao 類寫 findByUsername 的方法,傳入引數 usemame, JPA 已經實現了根據某個欄位去查詢的方法 所以該方法可以根據 usemame 欄位從資料庫中獲取 User 的資料,不需要做額外的編碼。如: 五、建立Service層    建立一個Service類,並注入dao,寫一個根據使用者名稱查詢使用者的方法: 六、建立Controller層      新建一個Controller類,寫一個Get型別的api介面,接收引數username,通過@PathVariable註解獲取RESTurl路徑上的引數:

重新啟動應用,手動的在資料庫新增一些資料,在瀏覽器輸入:http://localhost:8080/user/test    最後一個引數為資料庫存在的username  可以看到輸入test,可以查到資料庫test這一條資訊,並且輸出json物件。