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

    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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 建立一個Restful API的專案 [![hackmd-github-sync-badge](https://hackmd.io/iQp4KS1CTXWauL-EOdWXmg/badge)](https://hackmd.io/iQp4KS1CTXWauL-EOdWXmg) - [GitHub位置](https://github.com/camioljoyce/springboot-Restful-Demo) **首先按照之前做的這篇, 建立好基本的spring boot配置** - [建立一個SpringBoot + Spring + JPA 的Web專案](https://hackmd.io/i3T9xRyQR0OOVczCQmtkZQ) 設定好後,開始加入下列的class和interface 今天預計要做CRUD四個動作,一樣拿之前的Student來當範例 **今天要加入的class和interface如下圖:** ![](https://i.imgur.com/IfvDhXo.jpg) 在Entity層,一樣加入Student ```java= package camiol.example.com.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "Student") public class Student { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(name="Name") private String name; @Column(name="Math_Score") private int mathScore; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMathScore() { return mathScore; } public void setMathScore(int mathScore) { this.mathScore = mathScore; } } ``` 另外在vo層, 加上ResponseVo 用來回傳訊息 ```java= package camiol.example.com.vo; public class ResponseVo { private Object result; private String message; private String rcode; public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getRcode() { return rcode; } public void setRcode(String rcode) { this.rcode = rcode; } } ``` 在dao層,一樣加上StudentDao extends JpaRepository ```java= package camiol.example.com.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import camiol.example.com.entity.Student; @Repository public interface StudentDao extends JpaRepository<Student, Long>{ } ``` 在Service層, 我們加上CRUD的功能 ```java= package camiol.example.com.service; import java.util.List; import camiol.example.com.entity.Student; public interface StudentService { //查詢單一學生資料 Student findById(long id); //查詢所有學生資料 List<Student> findAll(); //新增或更新學生資料 void saveOrUpdate(Student s); //刪除學生資料 void delete(long id); } ``` 在service.impl層, 我們實作CRUD功能 ```java= package camiol.example.com.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import camiol.example.com.dao.StudentDao; import camiol.example.com.entity.Student; import camiol.example.com.service.StudentService; @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDao dao; @Override public Student findById(long id) { return dao.findById(id).orElse(new Student()); } @Override public List<Student> findAll() { return dao.findAll(); } @Override public void saveOrUpdate(Student s) { //如果有主鍵就更新該學生資料, 無主鍵的話就新增 dao.save(s); } @Override public void delete(long id) { dao.deleteById(id); } } ``` 最後在Controller層,要設定好restful api對應的CRUD 並且加上responseVo來回傳結果 ```java= package camiol.example.com.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import camiol.example.com.entity.Student; import camiol.example.com.service.StudentService; import camiol.example.com.vo.ResponseVo; @RestController @RequestMapping(value = "/student", produces = "application/json") public class StudentController { @Autowired private StudentService service; @GetMapping("/get") public ResponseVo getStudent(@RequestParam("id") long id) { ResponseVo result = new ResponseVo(); Student s = service.findById(id); if(s!=null) { result.setResult(s); result.setMessage("Query Success!"); result.setRcode("0000"); }else { result.setMessage("No Data!"); result.setRcode("0301"); } return result; } @GetMapping("/getAll") public ResponseVo getAllStudent() { ResponseVo result = new ResponseVo(); List<Student> list = service.findAll(); if(list!=null && !list.isEmpty()) { result.setResult(list); result.setMessage("Query Success!"); result.setRcode("0000"); }else { result.setMessage("No Data!"); result.setRcode("0301"); } return result; } @PostMapping("/add") public ResponseVo saveStudent(@RequestParam("name") String name,@RequestParam("mathScore") int mathScore) { ResponseVo result = new ResponseVo(); Student s = new Student(); s.setName(name); s.setMathScore(mathScore); service.saveOrUpdate(s); result.setMessage("Insert Success!"); result.setRcode("0000"); return result; } @PutMapping("/update") public ResponseVo updateStudent(@RequestParam("id") long id,@RequestParam("name") String name,@RequestParam("mathScore") int mathScore) { ResponseVo result = new ResponseVo(); Student bean = service.findById(id); if(bean!=null && bean.getId()>0) { bean.setName(name); bean.setMathScore(mathScore); service.saveOrUpdate(bean); result.setMessage("Update Success!"); result.setRcode("0000"); }else { result.setMessage("Update Fail! No Data!"); result.setRcode("0301"); } return result; } @DeleteMapping("/delete") public ResponseVo deleteStudent(@RequestParam("id") long id) { ResponseVo result = new ResponseVo(); Student bean = service.findById(id); if(bean!=null && bean.getId()>0) { service.delete(id); result.setMessage("Delete Success!"); result.setRcode("0000"); }else { result.setMessage("Delete Fail! No Data!"); result.setRcode("0301"); } return result; } } ``` 設定好後, 我們將專案啟動,用SoapUI 或 Postman來測試 **以下使用SoapUI來測試:** 先設定好REST來呼叫剛寫的api ![](https://i.imgur.com/ggab2gG.jpg) **開始一條條測試:** **1.查詢所有學生資料** ![](https://i.imgur.com/BIzniAr.jpg) **2.查詢指定學生資料** ![](https://i.imgur.com/feqVjlm.jpg) **3.新增學生資料** ![](https://i.imgur.com/NmF4U3o.jpg) **可以看到新增成功,這時再去查詢所有學生,可以看到剛新增的學生資料** ![](https://i.imgur.com/2u7YNlz.jpg) **4.更新指定學生資料** ![](https://i.imgur.com/qkOZvso.jpg) **可以看到更新成功,這時再去查詢所有學生,可以看到剛更新的7號學生資料** ![](https://i.imgur.com/Fiv3Vzg.jpg) **4.刪除指定學生資料** ![](https://i.imgur.com/gyjjnMA.jpg) **可以看到刪除成功,這時再去查詢所有學生,可以看到剛刪除的14號學生資料已不存在** ![](https://i.imgur.com/DYuKCoQ.jpg) **以上就是基本的Restful API的專案建立** ###### tags: `Spring boot` `Restful`

    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