如何使用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.

嗨,大家好! 在过去的一年中,我一直在学习用于全栈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开发中,我使用了:

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

    猫鼬-Mongo DB的ORM(对象关系映射)
  2. 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:

在右侧,添加以下依赖项:

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

    WEB —使用Spring的依赖项(用于开发Web应用程序的Spring Boot的旧框架)
  2. JPA — Java Persistence API

    JPA — Java持久性API
  3. 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”包中导入两个模块。

  1. SpringApplication

    Spring应用
  2. 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中使用的注释:

  1. @Component — Tells the compiler that the following class is a component which should be included when compiling the whole application.

    @Component —告诉编译器以下类是在编译整个应用程序时应包括的组件。

  2. @ComponentScan — This one does the Scan of which packages we are going to use in the following Java class.

    @ComponentScan —这将扫描以下Java类中要使用的软件包。

  3. @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
    @GeneratedValue
    private Long id;
@NotBlank
    private String book_name;
@NotBlank
    private String author_name;
@NotBlank
    private 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 data

Inside 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 {

@Autowired
    BookRepository 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:

我们在此处使用的注释说明:

  1. 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():这是在Java8Optional类中找到的一种方法,该方法被引入来处理异常。 可选类提供了各种实用程序方法来检查对象的存在或不存在,这有助于处理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 = update

That’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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值