SpringBoot使用MySQL访问数据

时间:2022-07-23
本文章向大家介绍SpringBoot使用MySQL访问数据,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本指南指导您创建连接到MySQL数据库的Spring应用程序(与大多数其他指南和许多示例应用程序使用的内存中的嵌入式数据库相反)。它使用Spring Data JPA访问数据库,但这只是许多可能的选择之一(例如,您可以使用普通的Spring JDBC)。

你将建立什么

您将创建一个MySQL数据库,构建一个Spring应用程序,并将其连接到新创建的数据库。

MySQL使用GPL许可,因此使用它发布的任何二进制程序也必须使用GPL。参见GNU通用公共许可证。

你需要什么

  • MySQL版本5.6或更高。如果安装了Docker,那么将数据库作为容器运行可能会很有用。
  • 大约15分钟
  • 最喜欢的文本编辑器或IDE
  • jdk1.8或更高
  • Gradle 4+或Maven 3.2+

如何完成本指南

与大多数Spring入门指南一样,您可以从头开始并完成每个步骤,或者可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都会得到工作代码。

  • 要从头开始,先从Spring Initializr开始。
  • 要跳过基本步骤,请做以下步骤: 下载并解压缩本指南的源存储库,或者使用Git克隆它:
Git clone https://github.com/springing-guides/gs-accessing-datamysql.git

cd到 gs-accessing-data-mysql/initial 跳转以创建数据库。

完成后,可以根据代码检查结果 gs-accessing-data-mysql/complete

从Spring Initializr开始

对于所有Spring应用程序,都应该从Spring Initializr开始。Initializr提供了一种快速获取应用程序所需的所有依赖项的方法,并为您进行了大量设置。这个示例需要Spring Web Starter、Spring Data JPA和MySQL驱动程序依赖项。下图显示了为这个示例项目设置的Initializr:

创建数据库

打开一个终端(Microsoft Windows中的命令提示符)并打开一个可以创建新用户的MySQL客户端。

例如,在Linux系统上,使用以下命令:

$ sudo mysql --password

它以root用户身份连接到MySQL,并允许用户从所有主机访问。对于生产服务器,这不是推荐的方法。

要创建一个新的数据库,在mysql提示符下运行以下命令:

mysql> create database db_example; -- Creates the new databasemysql> create user 'springuser'@'%' identified by 'ThePassword'; -- Creates the usermysql> grant all on db_example.* to 'springuser'@'%'; -- Gives all privileges to the new user on the newly created database

创建application.properties文件

Spring Boot为您提供所有设置的默认值。例如,默认数据库是H2。因此,当您希望使用任何其他数据库时,您必须在application.properties中定义连接属性。

创建一个名为src/main/resources/application的资源文件。属性,如下表所示:

spring.jpa.hibernate.ddl-auto=updatespring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_examplespring.datasource.username=springuserspring.datasource.password=ThePassword

在这里,spring.jpa.hibernate.ddl-auto可以是none、update、create或create-drop。有关详细信息,请参阅Hibernate文档。

  • none: MySQL的默认值。数据库结构未作任何更改。
  • update:Hibernate根据给定的实体结构更改数据库。
  • create:每次创建数据库,但在关闭时不删除它。
  • create-drop:创建数据库,并在SessionFactory关闭时删除它。

必须从create或update开始,因为还没有数据库结构。在第一次运行之后,您可以根据程序需求将其切换为update或none。当您想要对数据库结构进行一些更改时,请使用update。

H2和其他嵌入式数据库的默认值是create-drop。对于其他数据库,比如MySQL,默认值是none。

在数据库处于生产状态之后,将其设置为none,从连接到Spring应用程序的MySQL用户那里撤销所有特权,只允许MySQL用户SELECT, UPDATE, INSERT 和 DELETE,这是一个很好的安全实践。你可以在这篇指南的最后读到更多。

创建@Entity模型

您需要创建实体模型,如下所示(在src/main/java/ com/example/accessingdatamysl/user.java):

package com.example.accessingdatamysql;​import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;​@Entity // This tells Hibernate to make a table out of this classpublic class User {  @Id  @GeneratedValue(strategy=GenerationType.AUTO)  private Integer id;​  private String name;​  private String email;​  public Integer getId() {    return id;  }​  public void setId(Integer id) {    this.id = id;  }​  public String getName() {    return name;  }​  public void setName(String name) {    this.name = name;  }​  public String getEmail() {    return email;  }​  public void setEmail(String email) {    this.email = email;  }}

Hibernate自动将实体转换为表。

创建存储库

您需要创建存储用户记录的存储库,如下所示(在src/main/java/ com/example/accessingdatamysl/userrepository.java):

package com.example.accessingdatamysql;​import org.springframework.data.repository.CrudRepository;​import com.example.accessingdatamysql.User;​// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository// CRUD refers Create, Read, Update, Delete​public interface UserRepository extends CrudRepository<User, Integer> {​}

Spring在同名的bean中自动实现了这个存储库接口(在案例中有一个变化——它被称为userRepository)。

创建一个控制器

你需要创建一个控制器来处理HTTP请求到你的应用程序,如下所示(在src/main/java/ com/example/accessingdatamysl/maincontroller.java):

package com.example.accessingdatamysql;​import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;​@Controller // This means that this class is a Controller@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)public class MainController {  @Autowired // This means to get the bean called userRepository         // Which is auto-generated by Spring, we will use it to handle the data  private UserRepository userRepository;​  @PostMapping(path="/add") // Map ONLY POST Requests  public @ResponseBody String addNewUser (@RequestParam String name      , @RequestParam String email) {    // @ResponseBody means the returned String is the response, not a view name    // @RequestParam means it is a parameter from the GET or POST request​    User n = new User();    n.setName(name);    n.setEmail(email);    userRepository.save(n);    return "Saved";  }​  @GetMapping(path="/all")  public @ResponseBody Iterable<User> getAllUsers() {    // This returns a JSON or XML with the users    return userRepository.findAll();  }}

前面的示例显式地为这两个端点指定了POST和GET。默认情况下,@RequestMapping映射所有HTTP操作。

创建一个应用程序类

Spring Initializr为应用程序创建一个简单的类。下面的清单显示了Initializr为这个示例创建的类(在src/main/java/com/example/accessingdatamysql/AccessingDataMysqlApplication.java):

package com.example.accessingdatamysql;​import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;​@SpringBootApplicationpublic class AccessingDataMysqlApplication {​  public static void main(String[] args) {    SpringApplication.run(AccessingDataMysqlApplication.class, args);  }​}

对于本例,不需要修改AccessingDataMysqlApplication类。

@SpringBootApplication是一个方便的注释,添加了以下所有内容:

  • @Configuration:标记类作为应用程序上下文bean定义的源。
  • @EnableAutoConfiguration:告诉Spring Boot根据类路径设置、其他bean和各种属性设置开始添加bean。例如,如果spring-webmvc在类路径中,这个注释将应用程序标记为web应用程序并激活关键行为,比如设置一个DispatcherServlet。
  • @ComponentScan:告诉Spring在com/example包中寻找其他组件、配置和服务,让它找到控制器。

main()方法使用Spring引导的Spring application. run()方法来启动应用程序。您注意到没有一行XML吗?也没有web.xml文件。这个web应用程序是100%纯Java的,您不必配置任何管道或基础设施。

构建一个可执行JAR

您可以使用Gradle或Maven从命令行运行该应用程序。您还可以构建一个包含所有必要的依赖项、类和资源的可执行JAR文件并运行它。构建可执行jar使得在整个开发生命周期中,跨不同环境,等等,将服务作为应用程序进行发布、版本和部署变得更加容易。

如果你使用Gradle,你可以使用./gradlew bootRun来运行这个应用程序。或者,您可以使用./gradlew build构建JAR文件,然后运行JAR文件,如下所示:

java -jar build/libs/gs-accessing-data-mysql-0.1.0.jar

如果使用Maven,可以使用./mvnw spring-boot:run来运行应用程序。或者,您可以使用./mvnw clean包构建JAR文件,然后运行JAR文件,如下所示:

java -jar target/gs-accessing-data-mysql-0.1.0.jar

这里描述的步骤创建了一个可运行的JAR。您还可以构建一个经典的WAR文件。

运行应用程序时,将显示日志记录输出。服务应该在几秒钟内启动并运行。

测试应用程序

现在应用程序正在运行,您可以使用curl或类似的工具对其进行测试。你有两个HTTP端点,你可以测试:

GET localhost:8080/demo/all:得到所有的数据

POST localhost:8080/demo/add: 向数据添加一个用户

下面的curl命令添加了一个用户:

$ curl localhost:8080/demo/add -d name=First -d email=someemail@someemailprovider.com

答复如下:

Saved

以下命令显示所有用户:

$ curl 'localhost:8080/demo/all'

答复如下:

[{"id":1,"name":"First","email":"someemail@someemailprovider.com"}]

进行一些安全性更改

在生产环境中,您可能会受到SQL注入攻击。黑客可以注入DROP表或任何其他破坏性的SQL命令。因此,作为一种安全实践,在向用户公开应用程序之前,应该对数据库进行一些更改。

下面的命令撤销与Spring应用程序关联的用户的所有特权:

mysql> revoke all on db_example.* from 'springuser'@'%';

现在,Spring应用程序不能在数据库中执行任何操作。 应用程序必须有一些特权,所以使用下面的命令来授予应用程序所需的最小特权:

mysql> grant select, insert, delete, update on db_example.* to 'springuser'@'%';

删除所有特权并授予某些特权将使Spring应用程序获得仅更改数据库数据而不是结构(模式)所需的特权。

当你想改变数据库:

  1. 重新批准权限。
  2. spring.jpa.hibernate.ddl-auto 更改为update。
  3. 重新运行您的应用程序。

然后重复这里显示的两个命令,使您的应用程序在生产中再次安全使用。更好的方法是使用专门的迁移工具,比如Flyway或Liquibase。

总结

恭喜你!您刚刚开发了一个绑定到MySQL数据库的Spring应用程序,并准备投入生产!