Hi Everyone! For the past year, I have been learning JavaScript for full-stack web development. For a change, I started to master Java — the powerful Object Oriented Language.
嗨,大家好! 在過去的一年中,我一直在學習用于全棧Web開發JavaScript。 為了進行更改,我開始學習Java —功能強大的面向對象語言。
In that case, I found a very clean and elegant framework called Spring Boot to build a back end.
在那種情況下,我發現了一個非常干凈優雅的框架,稱為Spring Boot,用于構建后端。
Previously, in JavaScript development, I used:
以前,在JavaScript開發中,我使用了:
- Mongoose — an ORM (Object Relational Mapping) for Mongo DB 貓鼬-Mongo DB的ORM(對象關系映射)
- Sequelize — an ORM for MySQL Sequelize — MySQL的ORM
For Java-related development, there are lot of ORM’s like Hibernate, JPA (Java Persistence API) & Java Object Oriented Querying.
對于Java相關的開發,有很多ORM,例如Hibernate,JPA (Java持久性API)和Java面向對象的查詢。
I choose to build with JPA which is traditionally used in Java applications.
我選擇使用傳統上在Java應用程序中使用的JPA進行構建。
It was very interesting, and took about one week to finish as I had to learn Spring Boot (There are a lot of annotations “@” and other cool kinds of stuff to learn), JPA, and Hibernate along the way.
這非常有趣,大約花了一個星期的時間,因為我必須學習Spring Boot(有很多注釋“ @ ”和其他很酷的東西要學習),JPA和Hibernate。
All this magic is mostly done by the annotations (“@” symbol) used in Spring Boot.
所有這些魔術主要是由Spring Boot中使用的注釋 (“ @ ”符號)完成的。
創建一個Spring Boot Maven項目 (Creating a Spring Boot Maven Project)
Let’s create a Spring Boot Maven Project Application using this link.
讓我們使用此鏈接創建一個Spring Boot Maven項目應用程序。
“Maven” is a project management tool used to manage dependency management. It’s just like Node Package Manager (NPM) in the JS development environment.
“ Maven ”是用于管理依賴項管理的項目管理工具。 就像JS開發環境中的Node Package Manager( NPM )一樣。
We have package.json in NodeJS for dependency management and pom.xml in Spring Boot for dependency management.
在NodeJS中有package.json用于依賴關系管理, 在Spring Boot中有pom.xml用于依賴關系管理。
In Group, write whatever the name you want. Usually, the domain name of the organization is written right to left.
在“組”中,寫下您想要的任何名稱。 通常,組織的域名是從右到左寫的。
For example our domain name is www.javaAPI.com, so the group name could be com.javaAPI.www
例如,我們的域名是www.javaAPI.com ,因此組名稱可以是com.javaAPI.www。
Then in the Artifact type the name of the folder you want.
然后在Artifact中輸入所需文件夾的名稱 。
On the right side, add the following dependencies:
在右側,添加以下依賴項:
- WEB — To use the dependencies of Spring (The older framework of Spring Boot used to develop web applications) WEB —使用Spring的依賴項(用于開發Web應用程序的Spring Boot的舊框架)
- JPA — Java Persistence API JPA — Java持久性API
- MYSQL MySQL數據庫
Then click “Generate Project”. You will find a rar file — extract it. Then open that folder in your favorite IDE.
然后單擊“生成項目”。 您會找到一個rar文件-將其解壓縮。 然后在您喜歡的IDE中打開該文件夾。
Click on the com.rest.API and you will find an ApiApplication.java file as follows:
單擊com.rest.API ,您將找到一個ApiApplication.java文件,如下所示:
package com.rest.API;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApiApplication {
public static void main(String[] args) {SpringApplication.run(ApiApplication.class, args);}
}This code is enough to start your server. Normally spring boot runs on localhost:8080.
此代碼足以啟動您的服務器。 通常,Spring Boot在localhost:8080上運行。
Type in your terminal as follows:
在終端中輸入以下內容:
mvn spring-boot:run
mvn spring-boot:運行
See your localhost running in the web browser at port 8080. It looks blank as we haven’t done anything yet.
請查看運行在Web瀏覽器端口8080上的本地主機。由于我們尚未執行任何操作,因此它看起來空白。
讓我們探索文件及其標簽 (Let’s explore the files and their tags)
If you have a look at the pom.xml file you may notice that the dependencies you put in when creating the application in Spring Initialize like MySQL, JPA, and Web will be inside a <dependency> tag.
如果查看pom.xml文件,您可能會注意到在Spring Initialize中創建應用程序時放入的依賴項(如MySQL,JPA和Web)將位于<dependen cy>標記內。
The starter and tester dependencies are the core for creating the Spring Boot Application to serve on the server.
啟動程序和測試程序依賴性是創建在服務器上服務的Spring Boot Application的核心。
Now, let’s move to APIApplication.java which is the main file.
現在,讓我們轉到主文件APIApplication.java。
package com.rest.API;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApiApplication {
public static void main(String[] args) {SpringApplication.run(ApiApplication.class, args);}
}Here the name of the package is in the first line of the code. Using that package name, you can import any class, method, or instances in another package file.
包的名稱在代碼的第一行。 使用該程序包名稱,可以將任何類,方法或實例導入另一個程序包文件中。
After that, two modules are imported from “org.springframework.boot” package.
之后,從“ org.springframework.boot”包中導入兩個模塊。
- SpringApplication Spring應用
- SpringBootApplication SpringBoot應用程序
Since Spring boot is the latest application developing framework of Spring, it needs the packages of Spring Application as well as its specific packages.
由于Spring Boot是Spring的最新應用程序開發框架,因此它需要Spring Application的軟件包及其特定的軟件包。
After that @SpringBootApplication Annotation is used. This Annotation consists of annotation which is used in Spring:
之后,使用@SpringBootApplication Annotation。 該注釋包含在Spring中使用的注釋:
@Component — Tells the compiler that the following class is a component which should be included when compiling the whole application.
@Component —告訴編譯器以下類是在編譯整個應用程序時應包括的組件。
@ComponentScan — This one does the Scan of which packages we are going to use in the following Java class.
@ComponentScan —這將掃描以下Java類中要使用的軟件包。
@EnableAutoConfiguration — enables Spring Boot’s autoconfiguration mechanism to import important modules for the Spring Boot to run.
@EnableAutoConfiguration-使Spring Boot的自動配置機制能夠導入重要模塊以供Spring Boot運行。
These are the annotations used to start the Spring Boot Application to run on a server.
這些是用于啟動Spring Boot Application以便在服務器上運行的注釋。
Here is an article I have written about Annotation & their uses in Java.
這是我寫的有關注解及其在Java中的用法的文章。
讓我們為數據創建模型 (Let’s create Model for our data)
Let’s create a Model class to save, retrieve, update and delete the details of a book.
讓我們創建一個Model類來保存,檢索,更新和刪除書籍的詳細信息。
For that, I have to create a new package named model and inside that creating a Book.java class to put my code.
為此,我必須創建一個名為model的新程序包,并在其中創建一個Book.java類來放置我的代碼。
package com.rest.API.model;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
@Entity
@Table(name = "books")
public class Book {@Id@GeneratedValueprivate Long id;
@NotBlankprivate String book_name;
@NotBlankprivate String author_name;
@NotBlankprivate String isbn;
public Book(){super();}
public Book(Long id, String book_name, String author_name, String isbn) {super();this.id = id;this.book_name = book_name;this.author_name = author_name;this.isbn=isbn;}
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getBook_name() {return book_name;}
public void setBook_name(String book_name) {this.book_name = book_name;}
public String getAuthor_name() {return author_name;}
public void setAuthor_name(String author_name) {this.author_name = author_name;}
public String getIsbn() {return isbn;}
public void setIsbn(String isbn) {this.isbn = isbn;}
}Here I’m using JPA (Java Persistence API) which is a collection of classes and methods to continuously store data into a database.
在這里,我使用的是JPA(Java持久性API),它是用于將數據連續存儲到數據庫中的類和方法的集合。
@Entity — used to denote that this class is going to be an Entity in the database.
@Entity —用來表示該類將成為數據庫中的一個Entity。
@Table — which takes some values like the name you are going to name your table
@Table —它帶有一些值,例如您要為表命名的名稱
@Id — denotes that the id is the primary key / identifying key for this table
@Id —表示id是此表的主鍵/標識鍵
@NotBlank — is used to say that these attributes should not be blank.
@NotBlank-用來表示這些屬性不應為空。
Other than that there is an empty constructor which has a super method to satisfy the JPA customs. Getter and setter methods are usually in a POJO class (Plain old Java object).
除此之外,還有一個空的構造函數,該構造函數具有滿足JPA習慣的超級方法。 Getter和setter方法通常在POJO類( 普通的舊Java對象 )中。
創建存儲庫 (Creating the Repository)
Next, we are going to create a repository package to deal with database management in Java.
接下來,我們將創建一個存儲庫包來處理Java中的數據庫管理。
Create an Interface called BookRepository.java inside the repository package.
在存儲庫包中創建一個名為BookRepository.java的接口。
package com.rest.API.repository;
import com.rest.API.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}I have imported the JpaRepository package to use that repository in the BookRepository interface by connecting my most recently coded Book model to do CRUD operations.
我已導入JpaRepository包,以通過連接我最近編碼的Book模型進行CRUD操作來在BookRepository界面中使用該存儲庫。
There are already built-in methods in those repositories to do CRUD operations.
這些存儲庫中已經有內置方法可以執行CRUD操作。
Eg:
例如:
.findAll() - to get All datas
.save() - to save the got Data
.delete() - to delete the dataInside the <> tag we are taking the Model name we are going to use and the Primary key’s datatype.
在<>標記內,我們將使用將要使用的Model名稱和主鍵的數據類型。
@Repository: Annotation used to Indicate the DAO (Data Access Object) component in the persistence layer.
@Repository :用于指示持久層中的DAO( 數據訪問對象 )組件的注釋。
It tells the compiler that the interface is going to use the Repository to do database activities.
它告訴編譯器該接口將使用存儲庫來執行數據庫活動。
創建控制器和異常處理 (Creating Controller and Exception Handling)
Create a new package called controller, and inside that create a BookController.java file which contains the endpoints.
創建一個名為controller的新程序包,并 在其中創建一個包含端點的BookController.java文件。
package com.rest.API.controller;import com.rest.API.exception.BookNotFoundException;
import com.rest.API.model.Book;
import com.rest.API.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import javax.validation.Valid;
import java.util.List;@RestController
public class BookController {@AutowiredBookRepository bookRepository;// Get All Notes@GetMapping("/books")public List<Book> getAllNotes() {return bookRepository.findAll();}// Create a new Note@PostMapping("/books")public Book createNote(@Valid @RequestBody Book book) {return bookRepository.save(book);}// Get a Single Note@GetMapping("/books/{id}")public Book getNoteById(@PathVariable(value = "id") Long bookId) throws BookNotFoundException {return bookRepository.findById(bookId).orElseThrow(() -> new BookNotFoundException(bookId));}// Update a Note@PutMapping("/books/{id}")public Book updateNote(@PathVariable(value = "id") Long bookId,@Valid @RequestBody Book bookDetails) throws BookNotFoundException {Book book = bookRepository.findById(bookId).orElseThrow(() -> new BookNotFoundException(bookId));book.setBook_name(bookDetails.getBook_name());book.setAuthor_name(bookDetails.getAuthor_name());book.setIsbn(bookDetails.getIsbn());Book updatedBook = bookRepository.save(book);return updatedBook;}// Delete a Note@DeleteMapping("/books/{id}")public ResponseEntity<?> deleteBook(@PathVariable(value = "id") Long bookId) throws BookNotFoundException {Book book = bookRepository.findById(bookId).orElseThrow(() -> new BookNotFoundException(bookId));bookRepository.delete(book);return ResponseEntity.ok().build();}
}The first imported package is for the Book Not Found exception (for which we are going to create a file in a bit).
第一個導入的程序包用于“找不到書”異常(我們將稍后為其創建文件)。
Explanation of Annotations we used here:
我們在此處使用的注釋說明:
RestController: This annotation is used to denote every method in the annotated class as Domain Object.
RestController:此注釋用于將帶注釋的類中的每個方法表示為Domain Object。
So what is Domain Object…?
那么什么是域對象……?
It simply says that Domain Object == Business Object.
它只是說域對象==業務對象。
They are usually represented by entities and value objects related to the endpoint we are giving to get the data from the database.
它們通常由與我們要從數據庫獲取數據的端點相關的實體和值對象表示。
2. Autowired: This annotation is used to wire the bean classes automatically.
2. Autowired :此注釋用于自動連接Bean類。
For that, you need to know about “What is a bean Class..?”
為此,您需要了解“ 什么是bean類..? ”
Basically, a Java Bean Class is a simple class which encapsulates many objects into it.
基本上,Java Bean類是一個簡單的類,它將許多對象封裝到其中。
This is an article I wrote on Java Bean Classes.
這是我寫的關于Java Bean類的文章。
The following are the Mapping Annotations for the endpoints to perform CRUD Operations.
以下是端點執行CRUD操作的映射注釋。
3. GetMapping: This is an interface which contains the path of the endpoint to perform a Get method. This GetMapping interface uses the RequestMapping interface which can have the “path, value, params, headers” method to perform the Get method in earlier Spring versions.
3. GetMapping:這是一個接口 ,其中包含執行Get方法的端點的路徑。 此GetMapping接口使用RequestMapping接口,該接口可以具有“路徑,值,參數,標頭”方法,以在早期的Spring版本中執行Get方法。
Now it’s simplified by using GetMapping.
現在,使用GetMapping對其進行了簡化。
4. PostMapping: This is an interface which contains the path of the endpoint to perform the Post method.
4. PostMapping :這是一個接口 ,其中包含執行Post方法的端點的路徑。
5. PutMapping: This is an interface which contains the path of the endpoint to perform the Put method to Update.
5. PutMapping:這是一個接口 ,其中包含執行Put方法更新的端點的路徑。
6. DeleteMapping: This is an interface which contains the path of the endpoint to perform the Delete method.
6. DeleteMapping:這是一個接口 ,其中包含執行Delete方法的端點的路徑。
In the final lines, you probably noticed the “ResponseEntity” keyword.
在最后幾行中,您可能會注意到“ ResponseEntity ”關鍵字。
What is that…??
那是什么...?
It’s a Java class which inherits HttpEntity class to manipulate the HTTP Responses. Whether the request of the connection is “OK” or if there are any problems, throw an exception from the HttpEntity class.
這是一個Java類,繼承了HttpEntity類來操縱HTTP響應。 無論連接請求是“ OK ”還是存在任何問題,請從HttpEntity類引發異常 。
orElseThrow(): This is a method found in the Optional class in Java8 which was introduced to handle Exceptions. The optional class provides various utility methods to check the presence or absence of an object, which helps to deal with NullPointerException.
orElseThrow():這是在Java8的Optional類中找到的一種方法,該方法被引入來處理異常。 可選類提供了各種實用程序方法來檢查對象的存在或不存在,這有助于處理NullPointerException。
orElseThrow is a method that Returns value if present, otherwise invokes an exception.
orElseThrow是一種返回值(如果存在)的方法,否則調用異常。
如果沒有這樣的book_id,則創建一個NotFoundException (Creating a NotFoundException if there is no such book_id)
As orElseThrow method throws a NotFound Exception. The following is the Exception Handling part. Create a BookNotFoundException.java file inside exception package.
由于orElseThrow方法引發NotFound異常。 以下是異常處理部分。 在異常包中創建一個BookNotFoundException.java文件。
package com.rest.API.exception;
public class BookNotFoundException extends Exception {
private long book_id;
public BookNotFoundException(long book_id) {super(String.format("Book is not found with id : '%s'", book_id));}
}The created class extends the Superclass of Exception. In the constructor, I’m passing the book_id & prints the exception.
創建的類擴展了Exception的超類。 在構造函數中,我傳遞了book_id并打印異常。
So, that’s it…
就是這樣了…
We have finished the REST API part. Now you can build the app (which was explained in Part 1) and do some Testings with Postman.
我們已經完成了REST API部分。 現在,您可以構建應用程序(在第1部分中進行了說明),并使用Postman進行一些測試。
與MySql數據庫連接 (Connecting with MySql Database)
Inside the application.properties of your resources folder, add the following:
在資源文件夾的application.properties中,添加以下內容:
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/library
spring.datasource.username = root //normally put your MySQL username
spring.datasource.password = YOUR_MYSQL_PASSWORD
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = updateThat’s it.
而已。
We have built a basic REST API in Spring Boot. Congrats!
我們在Spring Boot中構建了一個基本的REST API。 恭喜!
If anything is wrong or need to be corrected, please let me know in the comments section.
如果有任何錯誤或需要更正,請在評論部分讓我知道。
Get in touch with me on twitter.
在Twitter上與我聯系。
Happy Coding!
編碼愉快!
翻譯自: https://www.freecodecamp.org/news/how-to-build-a-rest-api-with-spring-boot-using-mysql-and-jpa-f931e348734b/