ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 使用MySQL访问数据 本指南将引导您完成创建连接到MySQL数据库的Spring应用程序的过程(这与大多数其他指南和许多示例应用程序使用的内存中嵌入式数据库相反)。 它使用Spring Data JPA访问数据库,但这只是许多可能的选择之一(例如,您可以使用普通的Spring JDBC)。 ## 你会建立什么 您将创建一个MySQL数据库,构建一个Spring应用程序,并将其连接到新创建的数据库。 MySQL已获得GPL的许可,因此随它分发的任何程序二进制文件也必须使用GPL。 参见 GNU通用公共许可证 。 ## 你需要什么 * [MySQL](https://dev.mysql.com/downloads/) 5.6或更高版本。 如果您安装了Docker,将数据库作为 运行可能会很有用 [容器](https://hub.docker.com/_/mysql/) 。 * 约15分钟 * 最喜欢的文本编辑器或IDE * [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本 * [Gradle 4+](http://www.gradle.org/downloads) 或 [Maven 3.2+](https://maven.apache.org/download.cgi) * 您还可以将代码直接导入到IDE中: * [弹簧工具套件(STS)](https://spring.io/guides/gs/sts) * [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/) ## 如何完成本指南 像大多数Spring 一样 [入门指南](https://spring.io/guides) ,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。 无论哪种方式,您最终都可以使用代码。 要 **从头开始** ,请继续进行“ [从Spring Initializr开始”](https://spring.io/guides/gs/accessing-data-mysql/#scratch) 。 要 **跳过基础知识** ,请执行以下操作: * [下载](https://github.com/spring-guides/gs-accessing-data-mysql/archive/master.zip) 并解压缩本指南的源存储库,或使用 对其进行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-accessing-data-mysql.git](https://github.com/spring-guides/gs-accessing-data-mysql.git)` * 光盘进入 `gs-accessing-data-mysql/initial` * 继续 [创建数据库](https://spring.io/guides/gs/accessing-data-mysql/#initial) 。 **完成后** ,您可以根据中的代码检查结果 `gs-accessing-data-mysql/complete`. ## 从Spring Initializr开始 如果您使用Maven,请访问 [Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=accessing-data-mysql&name=accessing-data-mysql&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.accessing-data-mysql&dependencies=web,mysql,data-jpa) 以生成具有所需依赖项(Spring Web,Spring Data JPA和MySQL Driver)的新项目。 以下清单显示了 `pom.xml` 选择Maven时创建的文件: ~~~ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>accessing-data-mysql</artifactId> <version>0.0.1-SNAPSHOT</version> <name>accessing-data-mysql</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ~~~ 如果您使用Maven,请访问 [Spring Initializr](https://start.spring.io/#!type=gradle-project&language=java&platformVersion=2.4.2.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=accessing-data-mysql&name=accessing-data-mysql&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.accessing-data-mysql&dependencies=web,mysql,data-jpa) 以生成具有所需依赖项(Spring Web,Spring Data JPA和MySQL Driver)的新项目。 以下清单显示了 `build.gradle`选择Gradle时创建的文件: ~~~ plugins { id 'org.springframework.boot' version '2.4.3' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '1.8' repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' runtimeOnly 'mysql:mysql-connector-java' testImplementation 'org.springframework.boot:spring-boot-starter-test' } test { useJUnitPlatform() } ~~~ 配置该项​​目以适合本教程中的示例。 ### 手动初始化(可选) 如果要手动初始化项目而不是使用前面显示的链接,请按照以下步骤操作: 1. 导航到 [https://start.spring.io](https://start.spring.io) 。 该服务提取应用程序所需的所有依赖关系,并为您完成大部分设置。 2. 选择Gradle或Maven以及您要使用的语言。 本指南假定您选择了Java。 3. 单击 **Dependencies,** 然后选择 **Spring Web** , **Spring Data JPA** 和 **MySQL Driver** 。 4. 点击 **生成** 。 5. 下载生成的ZIP文件,该文件是使用您的选择配置的Web应用程序的存档。 如果您的IDE集成了Spring Initializr,则可以从IDE中完成此过程。 ## 创建数据库 打开终端(在Microsoft Windows中为命令提示符),然后以可以创建新用户的用户身份打开MySQL客户端。 例如,在Linux系统上,使用以下命令; ~~~ $ sudo mysql --password ~~~ 这以以下方式连接到MySQL root并允许从所有主机访问用户。 这 不是推荐的方法 对于生产服务器, 。 要创建新数据库,请在 `mysql` 迅速的: ~~~ mysql> create database db_example; -- Creates the new database mysql> create user 'springuser'@'%' identified by 'ThePassword'; -- Creates the user mysql> 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.properties`,如以下清单所示: ~~~ spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example spring.datasource.username=springuser spring.datasource.password=ThePassword ~~~ 这里, `spring.jpa.hibernate.ddl-auto` 可 `none`, `update`, `create`, 或者 `create-drop`。 有关 请参见 [Hibernate文档](https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl) 详细信息, 。 * `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/accessingdatamysql/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 class public 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/accessingdatamysql/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/accessingdatamysql/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; @SpringBootApplication public 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 Boot的 `SpringApplication.run()`启动应用程序的方法。 您是否注意到没有一行XML? 没有 `web.xml`文件。 该Web应用程序是100%纯Java,因此您无需处理任何管道或基础结构。 ### 建立可执行的JAR 您可以使用Gradle或Maven从命令行运行该应用程序。 您还可以构建一个包含所有必需的依赖项,类和资源的可执行JAR文件,然后运行该文件。 生成可执行jar使得在整个开发生命周期中,跨不同环境等等的情况下,都可以轻松地将服务作为应用程序进行发布,版本控制和部署。 If you use Gradle, you can run the application by using `./gradlew bootRun`. Alternatively, you can build the JAR file by using `./gradlew build` and then run the JAR file, as follows: ~~~ java -jar build/libs/gs-accessing-data-mysql-0.1.0.jar ~~~ 如果您使用Maven,则可以通过使用以下命令运行该应用程序 `./mvnw spring-boot:run`。 或者,您可以使用以下命令构建JAR文件: `./mvnw clean package` 然后运行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 TABLE`或任何其他破坏性的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应用程序!