日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

如何使用MySQL和JPA使用Spring Boot构建Rest API

發(fā)布時間:2023/11/29 数据库 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何使用MySQL和JPA使用Spring Boot构建Rest API 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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。 為了進行更改,我開始學(xué)習(xí)Java —功能強大的面向?qū)ο笳Z言。

In that case, I found a very clean and elegant framework called Spring Boot to build a back end.

在那種情況下,我發(fā)現(xiàn)了一個非常干凈優(yōu)雅的框架,稱為Spring Boot,用于構(gòu)建后端。

Previously, in JavaScript development, I used:

以前,在JavaScript開發(fā)中,我使用了:

  • Mongoose — an ORM (Object Relational Mapping) for Mongo DB

    貓鼬-Mongo DB的ORM(對象關(guān)系映射)
  • 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相關(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進行構(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.

    這非常有趣,大約花了一個星期的時間,因為我必須學(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)建一個Spring Boot Maven項目 (Creating a Spring Boot Maven Project)

    Let’s create a Spring Boot Maven Project Application using this link.

    讓我們使用此鏈接創(chuàng)建一個Spring Boot Maven項目應(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 ”是用于管理依賴項管理的項目管理工具。 就像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è),添加以下依賴項:

  • WEB — To use the dependencies of Spring (The older framework of Spring Boot used to develop web applications)

    WEB —使用Spring的依賴項(用于開發(fā)Web應(yīng)用程序的Spring Boot的舊框架)
  • JPA — Java Persistence API

    JPA — Java持久性API
  • MYSQL

    MySQL數(shù)據(jù)庫
  • 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.

    此代碼足以啟動您的服務(wù)器。 通常,Spring Boot在localhost:8080上運行。

    Type in your terminal as follows:

    在終端中輸入以下內(nèi)容:

    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上的本地主機。由于我們尚未執(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)用程序時放入的依賴項(如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)入另一個程序包文件中。

    After that, two modules are imported from “org.springframework.boot” package.

    之后,從“ org.springframework.boot”包中導(dǎo)入兩個模塊。

  • SpringApplication

    Spring應(yīng)用
  • SpringBootApplication

    SpringBoot應(yīng)用程序
  • 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 —告訴編譯器以下類是在編譯整個應(yīng)用程序時應(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的自動配置機制能夠?qū)胫匾K以供Spring Boot運行。

  • These are the annotations used to start the Spring Boot Application to run on a server.

    這些是用于啟動Spring Boot Application以便在服務(wù)器上運行的注釋。

    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)建一個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)建一個名為model的新程序包,并在其中創(chuàng)建一個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ù)庫中的一個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ò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)建一個存儲庫包來處理Java中的數(shù)據(jù)庫管理。

    Create an Interface called BookRepository.java inside the repository package.

    存儲庫包中創(chuàng)建一個名為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模型進行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 data

    Inside 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)建一個名為controller的新程序包 在其中創(chuàng)建一個包含端點的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).

    第一個導(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:此注釋用于將帶注釋的類中的每個方法表示為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ù)的端點相關(guān)的實體和值對象表示。

    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.

    這是我寫的關(guān)于Java Bean類的文章。

    The following are the Mapping Annotations for the endpoints to perform CRUD Operations.

    以下是端點執(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:這是一個接口 ,其中包含執(zhí)行Get方法的端點的路徑。 此GetMapping接口使用RequestMapping接口,該接口可以具有“路徑,值,參數(shù),標(biāo)頭”方法,以在早期的Spring版本中執(zhí)行Get方法。

    Now it’s simplified by using GetMapping.

    現(xiàn)在,使用GetMapping對其進行了簡化

    4. PostMapping: This is an interface which contains the path of the endpoint to perform the Post method.

    4. PostMapping :這是一個接口 ,其中包含執(zhí)行Post方法的端點的路徑。

    5. PutMapping: This is an interface which contains the path of the endpoint to perform the Put method to Update.

    5. PutMapping:這是一個接口 ,其中包含執(zhí)行Put方法更新的端點的路徑。

    6. DeleteMapping: This is an interface which contains the path of the endpoint to perform the Delete method.

    6. DeleteMapping:這是一個接口 ,其中包含執(zhí)行Delete方法的端點的路徑。

    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.

    這是一個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():這是在Java8Optional類中找到的一種方法,該方法被引入來處理異常。 可選類提供了各種實用程序方法來檢查對象的存在或不存在,這有助于處理NullPointerException。

    orElseThrow is a method that Returns value if present, otherwise invokes an exception.

    orElseThrow是一種返回值(如果存在)的方法,否則調(diào)用異常。

    如果沒有這樣的book_id,則創(chuàng)建一個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)建一個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)建的類擴展了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部分中進行了說明),并使用Postman進行一些測試。

    與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 = update

    That’s it.

    而已。

    We have built a basic REST API in Spring Boot. Congrats!

    我們在Spring Boot中構(gòu)建了一個基本的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上與我聯(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)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。

    主站蜘蛛池模板: 国产色无码精品视频国产 | 色偷偷人人澡人人爽人人模 | 色婷婷在线视频 | 在线免费观看视频 | 亚洲搞av| 一区二区手机在线 | 婷婷色av| 麻豆免费观看视频 | 极品蜜桃臀肥臀-x88av | 人妻少妇精品无码专区 | 原创少妇半推半就88av | 亚洲再线 | 亚洲国产精品成人无码区 | 欧美极品aaaaabbbbb | 黑人精品无码一区二区三区 | 国产精品久久一 | 欧美一级xxx| 91亚洲欧美激情 | 成人午夜精品视频 | 成人h视频在线观看 | 青草青在线 | 日本一区二区三区电影在线观看 | 丰满少妇麻豆av苏语棠 | 中文字幕一区二区三区精彩视频 | 美女精品| 少妇性xxxxxxxxx色武功 | 久久精品天天中文字幕人妻 | 国产精品自拍区 | 久久久久久久久久久久久久av | 日产电影一区二区三区 | 无码人妻h动漫 | 欧美日韩在线观看一区 | 经典三级av在线 | av在线网站观看 | 天天天天天天操 | 免费av毛片 | 国产午夜视频在线观看 | 日本黄色免费观看 | 蜜桃视频在线入口www | 欧美大胆a视频 | 又黄又色又爽的视频 | 日韩人妻精品无码一区二区三区 | 性欧美视频在线观看 | 天堂av网址 | 日韩av成人 | 黄色片网站在线播放 | 国产chinesehd天美传媒 | 亚洲人天堂 | 青娱网电信一区电信二区电信三区 | 亚洲视频综合 | 成人免费在线观看 | 幸福,触手可及 | 人人草人人爽 | 国产一区二区观看 | 九色视频网 | 人人妻人人澡人人爽精品欧美一区 | 欧美精品一级二级 | 欧美激情性做爰免费视频 | 91av免费在线观看 | 国产91丝袜在线18 | 日韩精品――色哟哟 | 91久久综合精品国产丝袜蜜芽 | 尤果网福利视频在线观看 | 伊人影院在线观看视频 | 久草剧场| 女色婷婷 | 国产免费网| 国产成人精品一区在线播放 | 波多野结衣av一区二区全免费观看 | 国产欧美日韩视频 | 久久精品女人毛片国产 | 久久久久久9999 | 久久av高潮av无码av喷吹 | 久久久久亚洲av片无码下载蜜桃 | 国产99免费 | 精品在线你懂的 | 亚洲免费观看 | 色xxxx | 天天干天天操心 | 91亚洲精品在线观看 | 91在线高清视频 | 大学生高潮无套内谢视频 | 999久久精品| 国产乱人伦精品一区二区 | 亚洲精品国产精品乱码不卡 | 欧美性高潮| 精品黑人一区二区三区观看时间 | 日韩在线一二三区 | 欧美做受高潮中文字幕 | 天堂8中文 | 久久在线播放 | yy4138理论片动漫理论片 | 伊人免费视频 | 可以免费看av | 日韩一二三区在线观看 | 被警察猛c猛男男男 | 日韩精品成人无码专区免费 | 97超碰中文字幕 | 国产乱码精品一区二区 |