csapty12
    • 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
    • Make a copy
    • 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 Make a copy 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
    # 1Building your First RESTful CRUD API. ## Part 1: Getting set up and creating an entity object This is a guide to help you get build your first RESTful CRUD API using Java Spring Boot. You will be introduced to libraries such as Spring Web, Lombok, Java Persistence API(JPA) and H2 (an in-memory database) to get you up and running as quickly as possible. This guide is split into a few different parts: 1. Introduction to the project 2. creating an entity object 3. Creating the repository layer 4. Creating the domain object 5. Creating the service layer 6. Creating the controller layer ## What are we building and how can we interact with it? We are going to build a **Reservation Management Service** (RMS).The RMS should have the following functionality and the client should be able to interact with the service using the following endpoints: - Create a new reservation - POST `http://localhost:8080/api/v1/reservation` - Retrieve details about the customer’s upcoming reservation - GET `http://localhost:8080/api/v1/reservation/{reservationId}` - Update the customer’s reservation - PUT `http://localhost:8080/api/v1/reservation/{reservationId}` - Delete the customer’s reservation - DELETE`http://localhost:8080/api/v1/reservation/{reservationId}` Any client should be able to hit these various endpoints to perfrom the actions that the service is capable of. ## Architecture overview # CAN WE GET STARTED ALREADY!? Damn.. ## Step 1: Create the RMS Spring Boot project. Go to [http://start.spring.io/](https://start.spring.io/) ![](https://i.imgur.com/Bf8vV9k.png) You can either create a new Spring Boot project using the Spring Initializr, or you can clone my repository to obtain the starter files (clone the repo and checkout branch [part-1-starter-files](https://github.com/csapty12/restaurantManagementSystem/tree/part-1-starter-files)) - *Project type* - Gradle - *Language* - java - *Spring Boot version* - 2.4.1 (use the lastest LTS version of Spring Boot) - *group ID* - com.rms - *Artifact ID* - reservationservice - *Service Name* - reservationservice - *Package name* - com.rms.reservationservice - *packaging* - WAR (this will be covered later. TLDR; as we are building a web app, we will eventually want to deploy this to a web server like Tomcat) - *Starter Dependencies* - - **Spring Web** - **Lombok** - a annotation rich library that helps remove more boilerplate code - **Spring Data JPA** - **H2** ## The Project Structure When you first import the project, there will already some folders and files created for you including: - ***bin*** - where your compiled code will be placed, as well as your WAR file when it is generated - ***gradle*** - enables us to use gradle commands without needing to install gradle on our local machines. - ***src/main***- where all our application code and application configuration will live (more on this next). - ***src/test*** - where all our automated tests for the API will live. - ***build.gradle*** - where we plugin our dependencies so that we do not need to install the library JAR's ourselves. - README.md - the readme for your project. We will dive deeper into these various files and directories through out the guide, to help you get to grips with their purposes, but for the time being, lets start building our Reservation Management Service! ### The build.gradle file: We will not be using this file much, however it is quite an important file as this is where dependencies will be imported from. This way, we can simply tell gradle to manage our dependencies for us so that we do not have to. Your buildd.radle file should look something like this: ``` plugins { id 'org.springframework.boot' version '2.4.1' id 'io.spring.dependency-management' version '1.0.10.RELEASE' id 'java' id 'war' } group = 'com.rms' version = '0.0.1-SNAPSHOT' sourceCompatibility = '11' configurations { compileOnly { extendsFrom annotationProcessor } } repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok' runtimeOnly 'com.h2database:h2' annotationProcessor 'org.projectlombok:lombok' providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' testImplementation 'org.springframework.boot:spring-boot-starter-test' } test { useJUnitPlatform() } ``` Notice that in the dependencies section, we can see that `spring-boot-starter-data-jpa`, `spring-boot-starter-web`, `lombok`, and `h2` are being used, as these are what we selected at project initialisation. These dependencies pull in multiple libraries so that we can get going with what really matters - building the RMS. ## Time to start coding - But where to begin? We have been told that for a customer to make a reservation, they need to provide the following data to the service which we need to store in our database: - A unique ID to identify the reservation - First Name - Last Name - Number of Guests - Reservation Date - Reservation Time To begin with, lets create a representation of this information in our code which will be stored in the database. - [ ] Create a new package called `entity` within `src/main/java/com/rms/reservationservice`. - [ ] Create a class called `ReservationEntity`. Within this class we can represent what our reservation data will look like. - ***Entity*** - an object representation of an item of a table in a database, also known as a **Data Access Object (DAO)**. The Entity may contain certain "metadata" fields that relate to the object being stored in the database, that the rest of the application does not necessarily need to know about e.g. createdAt, or updatedAt fields. An entity's only purpose is to make interactions with the database and thats it.We should not have any custom business logic within our entities. ``` package com.rms.reservationservice.entity; import lombok.*; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.time.LocalDateTime; @NoArgsConstructor(access = AccessLevel.PROTECTED) @AllArgsConstructor @Data @Builder @Entity @Table(name = "reservation") public class ReservationEntity { @Id private String id; private String firstName; private String lastName; private LocalDateTime reservationTime; private int numberOfGuests; } ``` The `ReservationEntity` class makes use of multiple annotations, to reduce the amount of boilerplate code that needs to be written. - ***@NoArgsConstructor(access = AccessLevel.PROTECTED)*** - exists only for JPA, we are not going to be using this ourselves, but JPA requires it be there. - ***@AllArgsConstructor*** - Gives us the option of creating ReservationEntity objects via a constrcutor call to be saved into the database. - ***@Data*** - provides out of the box methods such as getters, setters, toString, EqualsAndHashCode (see more [here](https://projectlombok.org/features/Data)). - ***@Builder*** - Enables you to use the builder design pattern to create immutable objects in a slightly more verbose manner. - ***@Table(name=‘reservation’)*** - Specifies the details of the table that will be used to persist the entity in the database. In this case, we are able to override the name of the table to be `reservation`. - ***@Entity*** - Indicates that this is a JPA entity, that will represent a row of the "reservation" table in the database. - ***@Id*** - Indicates to JPA that this is the `ReservationEntity`'s primary key, which is something that we will generate later. ***Note on the @Entity annotation*** - When we save an object in the database, we use an Object Relational Mapper (ORM) such as Hibernate to handle the mapping from an object to a relational database for us so we don’t have to. The Spring Data JPA starter dependency that we selected when creating the project provides the hibernate implementation for us! EVEN LESS BOILERPLATE CODE! By using these annotation, we are now ready to connect to a database and see the tables being created. If you did get stuck, please checkout the branch [part-1-creating-reservation-entity](https://github.com/csapty12/restaurantManagementSystem/tree/part-1-creating-reservation-entity) and compare your code against mine. In [Part 2: Creating the Repository Layer](https://hackmd.io/@csapty12/rJ7KwA_Cv), we are going to start to interact with a database by creating the repository layer and configuring the H2 database. See you there!

    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