本指南将引导您完成创建连接到MySQL数据库的Spring应用程序的过程(这与大多数其他指南和许多示例应用程序使用的内存嵌入式数据库相反)。它使用Spring Data JPA访问数据库,但这只是许多可能的选择之一(例如,您可以使用纯Spring JDBC)。
你会建立什么
您将创建一个MySQL数据库,构建一个Spring应用程序,并将其连接到新创建的数据库。
MySQL已获得GPL的许可,因此随它分发的任何程序二进制文件也必须使用GPL。请参阅GNU通用公共许可证 。 |
你需要什么
-
约15分钟
-
最喜欢的文本编辑器或IDE
-
JDK 1.8或更高版本
-
您还可以将代码直接导入到IDE中:
如何完成本指南
像大多数Spring 入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都可以使用工作代码。
要从头开始 ,请继续进行“ 从Spring Initializr开始” 。
要跳过基础知识 ,请执行以下操作:
-
下载并解压缩本指南的源存储库,或使用Git对其进行克隆:
git clone https://github.com/spring-guides/gs-accessing-data-mysql.git
-
光盘进入
gs-accessing-data-mysql/initial
-
继续创建数据库 。
完成后 ,您可以根据中的代码检查结果gs-accessing-data-mysql/complete
。
从Spring Initializr开始
对于所有Spring应用程序,您应该从Spring Initializr开始。Initializr提供了一种快速的方法来提取应用程序所需的所有依赖关系,并为您完成了许多设置。该示例需要Spring Web Starter,Spring Data JPA和MySQL Driver依赖项。下图显示了此示例项目的Initializr设置:

上图显示了选择Maven作为构建工具的Initializr。您也可以使用Gradle。它还显示了com.example 和accessing-data-mongodb 分别是Group和Artifact。在本示例的其余部分中,将使用这些值。 |
以下清单显示了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.1.7.RELEASE</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>
以下清单显示了build.gradle
选择Gradle时创建的文件:
plugins { id 'org.springframework.boot' version '2.1.7.RELEASE' id 'io.spring.dependency-management' version '1.0.8.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' }
创建数据库
打开终端(在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文档。
-
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/hello/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/hello/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使得在整个开发生命周期中,跨不同环境等等的情况下,可以轻松地将服务作为应用程序进行发布,版本化和部署。
如果您使用Gradle,则可以使用./gradlew bootRun
。或者,您可以通过使用以下命令构建JAR文件: ./gradlew build
然后运行JAR文件,如下所示:
如果使用Maven,则可以通过使用以下命令运行应用程序./mvnw spring-boot:run
。或者,您可以使用以下命令构建JAR文件: ./mvnw clean package
然后运行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 protected]
答复应如下:
Saved
以下命令显示所有用户:
$ curl 'localhost:8080/demo/all'
答复应如下:
[{"id":1,"name":"First","email":"[email protected]"}]
进行一些安全更改
在生产环境中,您可能会遭受SQL注入攻击。黑客可能会注入DROP TABLE
或任何其他破坏性的SQL命令。因此,作为安全实践,您应该在对用户公开应用程序之前对数据库进行一些更改。
以下命令撤消与Spring应用程序关联的用户的所有特权:
mysql> revoke all on db_example.* from 'springuser'@'localhost';
现在,Spring应用程序无法在数据库中执行任何操作。
该应用程序必须具有某些特权,因此请使用以下命令来授予该应用程序所需的最低特权:
mysql> grant select, insert, delete, update on db_example.* to 'springuser'@'localhost';
删除所有特权并授予一些特权将为您的Spring应用程序提供必要的特权,使其仅更改数据库的数据而不更改结构(架构)。
当您要更改数据库时:
-
授予权限。
-
改变
spring.jpa.hibernate.ddl-auto
至update
。 -
重新运行您的应用程序。
然后重复此处显示的两个命令,以确保您的应用程序可以安全地再次用于生产。更好的是,使用专用的迁移工具,例如Flyway或Liquibase。
摘要
恭喜你!您刚刚开发了一个绑定到MySQL数据库并可以投入生产的Spring应用程序!
也可以看看
以下指南也可能会有所帮助:
是否要编写新指南或为现有指南做出贡献?查看我们的贡献准则 。
所有指南均以代码的ASLv2许可证和写作的Attribution,NoDerivatives创作共用许可证发布 。 |