如何使用MySQL和JPA使用Spring Boot构建Rest API
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.
嗨,大家好! 在過去的一年中,我一直在學(xué)習(xí)用于全棧Web開發(fā)JavaScript。 為了進(jìn)行更改,我開始學(xué)習(xí)Java —功能強(qiáng)大的面向?qū)ο笳Z言。
In that case, I found a very clean and elegant framework called Spring Boot to build a back end.
在那種情況下,我發(fā)現(xiàn)了一個(gè)非常干凈優(yōu)雅的框架,稱為Spring Boot,用于構(gòu)建后端。
Previously, in JavaScript development, I used:
以前,在JavaScript開發(fā)中,我使用了:
For Java-related development, there are lot of ORM’s like Hibernate, JPA (Java Persistence API) & Java Object Oriented Querying.
對于Java相關(guān)的開發(fā),有很多ORM,例如Hibernate,JPA (Java持久性API)和Java面向?qū)ο蟮牟樵儭?/strong>
I choose to build with JPA which is traditionally used in Java applications.
我選擇使用傳統(tǒng)上在Java應(yīng)用程序中使用的JPA進(jìn)行構(gòu)建。
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.
這非常有趣,大約花了一個(gè)星期的時(shí)間,因?yàn)槲冶仨殞W(xué)習(xí)Spring Boot(有很多注釋“ @ ”和其他很酷的東西要學(xué)習(xí)),JPA和Hibernate。
All this magic is mostly done by the annotations (“@” symbol) used in Spring Boot.
所有這些魔術(shù)主要是由Spring Boot中使用的注釋 (“ @ ”符號)完成的。
創(chuàng)建一個(gè)Spring Boot Maven項(xiàng)目 (Creating a Spring Boot Maven Project)
Let’s create a Spring Boot Maven Project Application using this link.
讓我們使用此鏈接創(chuàng)建一個(gè)Spring Boot Maven項(xiàng)目應(yīng)用程序。
“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 ”是用于管理依賴項(xiàng)管理的項(xiàng)目管理工具。 就像JS開發(fā)環(huán)境中的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用于依賴關(guān)系管理, 在Spring Boot中有pom.xml用于依賴關(guān)系管理。
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:
在右側(cè),添加以下依賴項(xiàng):
Then click “Generate Project”. You will find a rar file — extract it. Then open that folder in your favorite IDE.
然后單擊“生成項(xiàng)目”。 您會找到一個(gè)rar文件-將其解壓縮。 然后在您喜歡的IDE中打開該文件夾。
Click on the com.rest.API and you will find an ApiApplication.java file as follows:
單擊com.rest.API ,您將找到一個(gè)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.
此代碼足以啟動您的服務(wù)器。 通常,Spring Boot在localhost:8080上運(yùn)行。
Type in your terminal as follows:
在終端中輸入以下內(nèi)容:
mvn spring-boot:run
mvn spring-boot:運(yùn)行
See your localhost running in the web browser at port 8080. It looks blank as we haven’t done anything yet.
請查看運(yùn)行在Web瀏覽器端口8080上的本地主機(jī)。由于我們尚未執(zhí)行任何操作,因此它看起來空白。
讓我們探索文件及其標(biāo)簽 (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中創(chuàng)建應(yīng)用程序時(shí)放入的依賴項(xiàng)(如MySQL,JPA和Web)將位于<dependen cy>標(biāo)記內(nèi)。
The starter and tester dependencies are the core for creating the Spring Boot Application to serve on the server.
啟動程序和測試程序依賴性是創(chuàng)建在服務(wù)器上服務(wù)的Spring Boot Application的核心。
Now, let’s move to APIApplication.java which is the main file.
現(xiàn)在,讓我們轉(zhuǎn)到主文件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.
包的名稱在代碼的第一行。 使用該程序包名稱,可以將任何類,方法或?qū)嵗龑?dǎo)入另一個(gè)程序包文件中。
After that, two modules are imported from “org.springframework.boot” package.
之后,從“ org.springframework.boot”包中導(dǎo)入兩個(gè)模塊。
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的最新應(yīng)用程序開發(fā)框架,因此它需要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 —告訴編譯器以下類是在編譯整個(gè)應(yīng)用程序時(shí)應(yīng)包括的組件。
@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的自動配置機(jī)制能夠?qū)胫匾K以供Spring Boot運(yùn)行。
These are the annotations used to start the Spring Boot Application to run on a server.
這些是用于啟動Spring Boot Application以便在服務(wù)器上運(yùn)行的注釋。
Here is an article I have written about Annotation & their uses in Java.
這是我寫的有關(guān)注解及其在Java中的用法的文章。
讓我們?yōu)閿?shù)據(jù)創(chuàng)建模型 (Let’s create Model for our data)
Let’s create a Model class to save, retrieve, update and delete the details of a book.
讓我們創(chuàng)建一個(gè)Model類來保存,檢索,更新和刪除書籍的詳細(xì)信息。
For that, I have to create a new package named model and inside that creating a Book.java class to put my code.
為此,我必須創(chuàng)建一個(gè)名為model的新程序包,并在其中創(chuàng)建一個(gè)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),它是用于將數(shù)據(jù)連續(xù)存儲到數(shù)據(jù)庫中的類和方法的集合。
@Entity — used to denote that this class is going to be an Entity in the database.
@Entity —用來表示該類將成為數(shù)據(jù)庫中的一個(gè)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是此表的主鍵/標(biāo)識鍵
@NotBlank — is used to say that these attributes should not be blank.
@NotBlank-用來表示這些屬性不應(yīng)為空。
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).
除此之外,還有一個(gè)空的構(gòu)造函數(shù),該構(gòu)造函數(shù)具有滿足JPA習(xí)慣的超級方法。 Getter和setter方法通常在POJO類( 普通的舊Java對象 )中。
創(chuàng)建存儲庫 (Creating the Repository)
Next, we are going to create a repository package to deal with database management in Java.
接下來,我們將創(chuàng)建一個(gè)存儲庫包來處理Java中的數(shù)據(jù)庫管理。
Create an Interface called BookRepository.java inside the repository package.
在存儲庫包中創(chuàng)建一個(gè)名為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.
我已導(dǎo)入JpaRepository包,以通過連接我最近編碼的Book模型進(jìn)行CRUD操作來在BookRepository界面中使用該存儲庫。
There are already built-in methods in those repositories to do CRUD operations.
這些存儲庫中已經(jīng)有內(nèi)置方法可以執(zhí)行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.
在<>標(biāo)記內(nèi),我們將使用將要使用的Model名稱和主鍵的數(shù)據(jù)類型。
@Repository: Annotation used to Indicate the DAO (Data Access Object) component in the persistence layer.
@Repository :用于指示持久層中的DAO( 數(shù)據(jù)訪問對象 )組件的注釋。
It tells the compiler that the interface is going to use the Repository to do database activities.
它告訴編譯器該接口將使用存儲庫來執(zhí)行數(shù)據(jù)庫活動。
創(chuàng)建控制器和異常處理 (Creating Controller and Exception Handling)
Create a new package called controller, and inside that create a BookController.java file which contains the endpoints.
創(chuàng)建一個(gè)名為controller的新程序包,并 在其中創(chuàng)建一個(gè)包含端點(diǎn)的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).
第一個(gè)導(dǎo)入的程序包用于“找不到書”異常(我們將稍后為其創(chuàng)建文件)。
Explanation of Annotations we used here:
我們在此處使用的注釋說明:
RestController: This annotation is used to denote every method in the annotated class as Domain Object.
RestController:此注釋用于將帶注釋的類中的每個(gè)方法表示為Domain Object。
So what is Domain Object…?
那么什么是域?qū)ο蟆?#xff1f;
It simply says that Domain Object == Business Object.
它只是說域?qū)ο?#61;=業(yè)務(wù)對象。
They are usually represented by entities and value objects related to the endpoint we are giving to get the data from the database.
它們通常由與我們要從數(shù)據(jù)庫獲取數(shù)據(jù)的端點(diǎn)相關(guān)的實(shí)體和值對象表示。
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類是一個(gè)簡單的類,它將許多對象封裝到其中。
This is an article I wrote on Java Bean Classes.
這是我寫的關(guān)于Java Bean類的文章。
The following are the Mapping Annotations for the endpoints to perform CRUD Operations.
以下是端點(diǎn)執(zhí)行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:這是一個(gè)接口 ,其中包含執(zhí)行Get方法的端點(diǎn)的路徑。 此GetMapping接口使用RequestMapping接口,該接口可以具有“路徑,值,參數(shù),標(biāo)頭”方法,以在早期的Spring版本中執(zhí)行Get方法。
Now it’s simplified by using GetMapping.
現(xiàn)在,使用GetMapping對其進(jìn)行了簡化。
4. PostMapping: This is an interface which contains the path of the endpoint to perform the Post method.
4. PostMapping :這是一個(gè)接口 ,其中包含執(zhí)行Post方法的端點(diǎn)的路徑。
5. PutMapping: This is an interface which contains the path of the endpoint to perform the Put method to Update.
5. PutMapping:這是一個(gè)接口 ,其中包含執(zhí)行Put方法更新的端點(diǎn)的路徑。
6. DeleteMapping: This is an interface which contains the path of the endpoint to perform the Delete method.
6. DeleteMapping:這是一個(gè)接口 ,其中包含執(zhí)行Delete方法的端點(diǎn)的路徑。
In the final lines, you probably noticed the “ResponseEntity” keyword.
在最后幾行中,您可能會注意到“ ResponseEntity ”關(guān)鍵字。
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.
這是一個(gè)Java類,繼承了HttpEntity類來操縱HTTP響應(yīng)。 無論連接請求是“ OK ”還是存在任何問題,請從HttpEntity類引發(fā)異常 。
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類中找到的一種方法,該方法被引入來處理異常。 可選類提供了各種實(shí)用程序方法來檢查對象的存在或不存在,這有助于處理NullPointerException。
orElseThrow is a method that Returns value if present, otherwise invokes an exception.
orElseThrow是一種返回值(如果存在)的方法,否則調(diào)用異常。
如果沒有這樣的book_id,則創(chuàng)建一個(gè)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方法引發(fā)NotFound異常。 以下是異常處理部分。 在異常包中創(chuàng)建一個(gè)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.
創(chuàng)建的類擴(kuò)展了Exception的超類。 在構(gòu)造函數(shù)中,我傳遞了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.
我們已經(jīng)完成了REST API部分。 現(xiàn)在,您可以構(gòu)建應(yīng)用程序(在第1部分中進(jìn)行了說明),并使用Postman進(jìn)行一些測試。
與MySql數(shù)據(jù)庫連接 (Connecting with MySql Database)
Inside the application.properties of your resources folder, add the following:
在資源文件夾的application.properties中,添加以下內(nèi)容:
## 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中構(gòu)建了一個(gè)基本的REST API。 恭喜!
If anything is wrong or need to be corrected, please let me know in the comments section.
如果有任何錯誤或需要更正,請?jiān)谠u論部分讓我知道。
Get in touch with me on twitter.
在Twitter上與我聯(lián)系。
Happy Coding!
編碼愉快!
翻譯自: https://www.freecodecamp.org/news/how-to-build-a-rest-api-with-spring-boot-using-mysql-and-jpa-f931e348734b/
總結(jié)
以上是生活随笔為你收集整理的如何使用MySQL和JPA使用Spring Boot构建Rest API的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到邻居来我家吃饭是什么意思
- 下一篇: javascript 作用_JavaSc