# 使用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應用程序!
- springboot概述
- springboot構建restful服務
- spring構建一個RESTful Web服務
- spring定時任務
- 消費RESTful Web服務
- gradle構建項目
- maven構建項目
- springboot使用jdbc
- springboot應用上傳文件
- 使用LDNA驗證用戶
- 使用 spring data redis
- 使用 spring RabbitTemplate消息隊列
- 用no4j訪問nosql數據庫
- springboot驗證web表單
- Spring Boot Actuator構j建服務
- 使用jms傳遞消息
- springboot創建批處理服務
- spring security保護web 安全
- 在Pivotal GemFire中訪問數據
- 使用Spring Integration
- 使用springboot jpa進行數據庫操作
- 數據庫事務操作
- 操作mongodb
- springmvc+tymleaf創建web應用
- 將Spring Boot JAR應用程序轉換為WAR
- 創建異步服務
- spring提交表單
- 使用WebSocket構建交互式Web應用程序
- 使用REST訪問Neo4j數據
- jquery消費restful
- springboot跨域請求
- 消費SOAP Web服務
- springboot使用緩存
- 使用Vaadin創建CRUD UI
- 使用REST訪問JPA數據
- 使用REST訪問Pivotal GemFire中的數據
- 構建soap服務
- 使用rest訪問mongodb數據
- 構建springboot應用docker鏡像
- 從STS部署到Cloud Foundry
- springboot測試web應用
- springboot訪問mysql
- springboot編寫自定義模塊并使用
- 使用Google Cloud Pub / Sub進行消息傳遞
- 構建反應式RESTful Web服務
- 使用Redis主動訪問數據
- Spring Boot 部署到Kubernetes
- 使用反應式協議R2DBC訪問數據
- Spring Security架構
- spring構建Docker鏡像詳解
- Spring Boot和OAuth2
- springboot應用部署到k8s
- spring構建rest服務詳解