Ian
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Spring Data JPA ## 前言 實作一個基本資料庫存取功能的程式,需要寫大量的程式做資料庫的連接,甚至還需了解不同資料庫的語法,才能看到功能的雛形,而每多一個功能也需要做許多重複的事情。此篇介紹 Spring Data JPA 可以大幅降低資料庫存取功能的工作,讓開發人員更專注在商業邏輯上。 ## JPA 是什麼? JPA(Java Persistence API) 是 SUN 針對 ORM 技術提出的規範,目的為簡化持久化的開發工作以及整合各家 ORM 技術(Hibernate、TopLink、OpenJpa...)。 ## Spring Data JPA Spring Data JPA 是 Spring 根據 ORM 框架和 JPA 規範而封裝的 JPA 應用框架,目的是降低存取資料層的工作量,讓開發人員只需寫出 repository 的介面,而 Spring 自動幫你實作其功能。 ### JpaRepository interface [PagingAndSortingRepository](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/PagingAndSortingRepository.html) ```java public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T> ``` #### SimpleJpaRepository [SimpleJpaRepository](https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/support/SimpleJpaRepository.html) 中有實作 JpaRepository 介面,實作內容包含簡單的 crud,包含 `count()`、`existsById(ID id)`、`findAll(Specification<T> spec, Pageable pageable)` 等等,當繼承 JpaRepository 後不必實作上述方法也能使用。 ### 使用方法 #### Maven ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.2.6.RELEASE</version> </dependency> ``` #### Gradle ```groovy= compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.2.6.RELEASE' ``` #### Entity 建立 Entity 達成 orm ```java @Data @Entity @EntityListeners(AuditingEntityListener.class) public class User { @Id @GeneratedValue private long id; private String name; @ManyToOne private Country country; private int age; @CreatedDate private LocalDateTime createdDate; } ``` 可用的 Annotation * `@Entity` 是告訴 Spring 這是資料模型層的宣告。 * `@Table` 對應到資料庫中的名稱,也可指定要建立的 index。 * `@Column` 對應到 Table 的欄位中的欄位名稱。 * `@Id` 此資料表的 Primary Key。 * `@GeneratedValue` 告訴此Column的生成方式 ,如果設定成 `GenerationType.AUTO` 讓容器來自動產生。 * `@CreatedDate` 在 Entity 被建立或修改時會自動賦值。 * `@ManyToOne`、`@OneToMany` 相當於資料表中 FOREIGN KEY 設定 * `CascadeType.PERSIST` 在儲存時一併儲存被參考的物件。 * `CascadeType.MERGE` 在合併修改時一併合併修改被參考的物件。 * `CascadeType.REMOVE` 在移除時一併移除被參考的物件。 * `CascadeType.REFRESH` 在更新時一併更新被參考的物件。 * `CascadeType.ALL` 無論儲存、合併、更新或移除,一併對被參考物件作出對應動作。 #### Dao 建立 UserDao 繼承 JpaRepository ```java @Repository public interface UserDao extends JpaRepository<User, Integer> { List<User> findByCountryAndAgeLessThan(Country country, int age); } ``` #### 自定義 Method 規則 | Keyword | Sample | SQL | | - | - |- | | And | findByNameAndCountry | ...WHERE name = ?1 AND country =?2 | | Between | findByAgeBetween | ...WHERE age <= ?1 AND age >=?2 | | LessThan | findByAgeLessThan | ...WHERE age < ?1 | | Like | findByNameLike | ...WHERE name LIKE ?1 | #### 特殊用法 * [Pageable](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Pageable.html) * [Sort](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Sort.html) ```java Page<User> findByName(String name, Pageable pageable); List<User> findByName(String name, Sort sort); ``` ```java public void findUser() { int page = 0; int size = 10; Sort sort = new Sort(Direction.DESC, "age"); Pageable pageable = new PageRequest(page, size, sort); Page<User> page = userDao.findAll(pageable); Page<User> page = userDao.findByCountry(country, pageable); } ``` #### 自行寫 sql ```java @Query(value="select * from user where name like %?1", nativeQuery=true) public List<User> findByName(String name); ``` ## Spring Data JPA - JpaRepository 原理 ### 問題一 * 為什麼不需要 implement 就可以完成 CRUD? #### 呼叫流程 1. 透過 `@EnableJpaRepositories` import `JpaRepositoriesRegistrar` 2. `JpaRepositoriesRegistrar` 繼承於 `RepositoryBeanDefinitionRegistrarSupport` 3. `RepositoryBeanDefinitionRegistrarSupport` 的 `registerBeanDefinitions` 向 spring 註冊 `JpaRepositoryFactoryBean` 4. `JpaRepositoryFactoryBean.afterPropertiesSet()` 會調用 `RepositoryFactorySupport.getRepository()` 5. `JpaRepositoryFactory` 繼承 `RepositoryFactorySupport` 並且預設的 repository 為 `SimpleJpaRepository` 6. 所以繼承 `JpaRepository` 的 class 不需要實作就可以完成 CRUD 的功能。 ### 問題二 * SimpleJpaRepository 沒有實作的功能(`ex findByName(String name)`),為什麼也能存取 DB。 #### 原因 1. 在問題一的 `RepositoryFactorySupport.getRepository()` 中會調用 `QueryExecutorMethodInterceptor`,此攔截器就是拿來判斷 method 的類型。 ![](https://i.imgur.com/ugn7TtW.png =60%x) 2. `findByName()` 的類型是自定義的查詢,所以會跑到 `SingleEntityExecution()` 3. 繼續往下追會發現底層使用 hibernate 的 `CriteriaQueryImpl` 來拼湊出 sql。 ## 總結 使用 JpaRepository 的好處: * 減少開發時間 * 增加程式可讀性 ## 參考資料 [Spring Data JPA - Reference Documentation](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories) [SpringDataJpa: JpaRepository增删改查](https://blog.csdn.net/fly910905/article/details/78557110) [Spring Data JPA 之 JpaRepository](https://blog.csdn.net/hbtj_1216/article/details/79773839) [CascadeType 與 FetchType](https://openhome.cc/Gossip/EJB3Gossip/CascadeTypeFetchType.html) [【spring boot 系列】spring data jpa 全面解析(实践 + 源码分析)](https://segmentfault.com/a/1190000015047290) [[Java] JPA 是什麼?](https://ithelp.ithome.com.tw/articles/10229808)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully