Kai Chen
    • 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

      This note has no invitees

    • 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
    • Note Insights
    • 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 Note Insights 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

    This note has no invitees

  • 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
    # 六角鼠年鐵人賽 Week 26 - Spring Boot - Spring Data & JPA 範例 ==大家好,我是 "為了拿到金角獎盃而努力著" 的文毅青年 - Kai== ## Bill Gates :::info If you can't make it good, at least make it look good. ::: ## 主題 上週已經提完了關於 JPA、ORM、Spring Data & JPA 的部分。 這週就來做一個簡單的實作範例。 如何透過 Entity、Repository 的方式掌控著以往使用 DAO 處理 DB 的方式。 ## 範例 > 延續前幾週的範例方式,Kai 全部都實作在同一個專案中,有興趣的人可以私信我分享。 ![](https://i.imgur.com/JjzfGBe.png) ### build.gradle ```xml dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' runtimeOnly 'com.h2database:h2' } ``` 在 dependencies 加入 spring data jpa 的套件,並還有使用 H2 DB 作為範例DB使用。 > 有興趣的人可以研究一下 H2 DB,他是一個非常輕量版,幾乎只需要使用套件即可運行,不需要任何安裝動作的 DB ### Entity Kai 建立一個屬於員工的 Entity 作為示範範例 ```java= package kai.com.jpa.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.sql.Date; @Entity public class Employee { public Employee (){} public Employee(String name, String team, Date birthDate){ this.emp_name = name; this.emp_team = team; this.emp_birthDate = birthDate; } @Id @GeneratedValue(strategy= GenerationType.AUTO) private Long emp_id; private String emp_name; private String emp_team; private Date emp_birthDate; public Long getEmp_id() { return emp_id; } public void setEmp_id(Long emp_id) { this.emp_id = emp_id; } public String getEmp_name() { return emp_name; } public void setEmp_name(String emp_name) { this.emp_name = emp_name; } public String getEmp_team() { return emp_team; } public void setEmp_team(String emp_team) { this.emp_team = emp_team; } public Date getEmp_birthDate() { return emp_birthDate; } public void setEmp_birthDate(Date emp_birthdate) { this.emp_birthDate = emp_birthdate; } } ``` ### Repository ```java= package kai.com.jpa.repository; import kai.com.jpa.entity.Employee; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import java.util.List; import java.util.Optional; public interface EmployeeRepository extends CrudRepository<Employee, Long> { List<Employee> findAll(); Optional<Employee> findById(Long id); void deleteById(Long id); @Query(value="SELECT * FROM EMPLOYEE as e WHERE e.EMP_ID BETWEEN ?1 AND ?2 " ,nativeQuery = true) List<Employee> findByPriorityBetween(Long number1, Long number2); } ``` ### Controller 因為需要一些資料當作測試用,因此有多寫一支 API 專門用來建立資料這樣,其實也可以透過 Class build 起來時就直接建立好。 不過為了當作範例,就想說必須要有明確地做點什麼。 ```java= package kai.com.jpa.controller; import kai.com.jpa.entity.Employee; import kai.com.jpa.repository.EmployeeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.sql.Date; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/getEmp") public class JPATestController { @Autowired EmployeeRepository employeeRepository; @GetMapping("/build") public String buildTableAndData(){ /*** 建立測試資料 ***/ Employee emp = new Employee(); emp.setEmp_name("Michael"); emp.setEmp_team("IT"); emp.setEmp_birthDate(new Date(19920101)); employeeRepository.save(emp); emp = new Employee(); emp.setEmp_name("Cherry"); emp.setEmp_team("Salse"); emp.setEmp_birthDate(new Date(19900101)); employeeRepository.save(emp); emp = new Employee(); emp.setEmp_name("Stanley"); emp.setEmp_team("Product"); emp.setEmp_birthDate(new Date(19960101)); employeeRepository.save(emp); return "Done build."; } @GetMapping() public List<Employee> getAll(){ return employeeRepository.findAll(); } @GetMapping("/{number1}/{number2}") public List<Employee> getByRange(@PathVariable("number1") Long number1, @PathVariable("number2") Long number2){ return employeeRepository.findByPriorityBetween(number1,number2); } @GetMapping("/{id}") public Optional<Employee> getById(@PathVariable("id") Long Id){ return employeeRepository.findById(Id); } @DeleteMapping("/{id}") public String deleteById(@PathVariable("id") Long Id){ employeeRepository.deleteById(Id); if(!employeeRepository.findById(Id).isPresent()) return "Delete Successfully."; return "Delete failed."; } } ``` ### 測試 1. 建立測試用的資料 ![](https://i.imgur.com/OWBh3ZE.png) 2. 搜尋全部人的資料 ![](https://i.imgur.com/guokokw.png) 3. 搜尋 ID 為 1 的單筆資料 ![](https://i.imgur.com/gJesOyU.png) 4. 搜尋 ID 為 1 到 2 的範圍資料 ![](https://i.imgur.com/qDPFJy5.png) 5. 刪除 ID 為 1 的單筆資料 ![](https://i.imgur.com/B77aC9v.png) ![](https://i.imgur.com/VZ3jaIl.png) > 再查詢全部後會發現少了 ID 為 1 的資料 > 另外提一點是,這邊 Kai 的設計方法做的差了,實際應用上的取資料路徑盡量避免與處理 update 和 delete 的路徑一樣 ## 結語 :::danger 這篇算是簡單的給出了一個應用上的範例,我們可以看到透過 Repository 的方式,少寫了非常多的 DAO class,以及不會因為少了 DAO 就無法進行客製化的動作,Repository 的 QUERY 提供了 JPQL 超級多的作法以滿足開發者的需求! 詳細的可以參閱 Kai 找到的一篇整理非常詳細的 @Query 應用文章 [Spring Data JPA Custom Queries using @Query Annotation](https://attacomsian.com/blog/spring-data-jpa-query-annotation) 希望這兩篇關於 JPA 的文章可以帶給尚未嘗試使用 JPA 的朋友們一點了解~ 下一篇來介紹 @Query 比較細節的部分 [六角鼠年鐵人賽 Week 27 - Spring Boot - Spring Data & JPA @Query Annotation](/_3nYiCiiSciHAbHaEcLZfQ) ::: 首頁 [Kai 個人技術 Hackmd](/2G-RoB0QTrKzkftH2uLueA) ###### tags: `Spring Boot`,`Spring Data`,`w3HexSchool`

    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