使用MySQL访问数据

本指南将引导您完成创建与MySQL数据库连接的Spring应用程序的过程,而不是内存中的嵌入式数据库,其中所有其他指南和许多示例应用程序都使用该数据库。它使用Spring Data JPA来访问数据库,但这只是众多可能选择之一(例如,您可以使用普通的Spring JDBC)。

你会建立什么

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

MySQL使用GPL许可,因此您使用它分发的任何程序二进制文件也必须使用GPL。请参阅GNU通用公共许可证

你需要什么

  • MySQL版本5.6或更高版本。如果您安装了docker,将数据库作为容器运行可能会很有用

如何完成本指南

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

从头开始,请继续阅读使用Gradle构建

跳过这些基础知识,请执行以下操作:

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

用Gradle构建

用Maven构建

用您的IDE构建

创建数据库

转到终端(cmdMicrosoft Windows中的命令提示符)。与可以创建新用户的用户打开MySQL客户端。

例如:在Linux上,使用该命令

$ sudo mysql --password
这作为根连接到MySQL,这不是生产服务器的推荐方式

创建一个新的数据库

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

创建application.properties文件

Spring Boot提供了所有默认设置,数据库中的默认值是H2,所以当你想改变它并使用任何其他数据库时,你必须在application.properties文件中定义连接属性

在sources文件夹中,创建一个资源文件 src/main/resources/application.properties

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword

在这里,spring.jpa.hibernate.ddl-auto可以是noneupdatecreatecreate-drop,请参阅Hibernate文档,了解详细信息。

  • none这是MySQL数据库结构的默认设置,不会更改。

  • update Hibernate根据给定的Entity结构改变数据库。

  • create 每次创建数据库,但在关闭时不要丢弃它。

  • create-drop创建数据库,然后在SessionFactory关闭时删除它

我们从这里开始,create因为我们还没有数据库结构。第一次运行后,我们可以切换到updatenone根据程序要求。update当您想对数据库结构进行一些更改时使用

对于H2其他嵌入式数据库的默认值create-drop,但是对于其他类似MySQLnone

在你的数据库处于生产状态之后,这是一个很好的安全实践,你可以none通过连接到Spring应用程序的MySQL用户取消所有权限,然后只给予他SELECT,UPDATE,INSERT,DELETE。

这将在本指南的末尾详细介绍。

创建@Entity模型

src/main/java/hello/User.java

package hello;

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/hello/UserRepository.java

package hello;

import org.springframework.data.repository.CrudRepository;

import hello.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, Long> {

}

这是版本库接口,这将由Spring在具有相同名称且具有不断变化大小的Bean中自动实现。bean的名称将为 userRepository

为您的Spring应用程序创建一个新的控制器

src/main/java/hello/MainController.java

package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import hello.User;
import hello.UserRepository;

@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;

	@GetMapping(path="/add") // Map ONLY GET 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();
	}
}
上面的例子没有明确指定GETvs PUTPOST等等,因为它@GetMapping是一个快捷方式@RequestMapping(method=GET)@RequestMapping默认映射所有HTTP操作。使用@RequestMapping(method=GET)其他快捷方式注释缩小此映射。

使应用程序可执行

虽然可以将此服务作为传统WAR文件打包以部署到外部应用程序服务器,但下面演示的更简单的方法会创建独立应用程序。您将所有内容都打包在一个单独的,可执行的JAR文件中,并由一个优秀的Java main()方法驱动一路上,您使用Spring的支持将Tomcat servlet容器作为HTTP运行时嵌入,而不是部署到外部实例。

src/main/java/hello/Application.java

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

构建一个可执行的JAR

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

如果您正在使用Gradle,则可以使用运行该应用程序./gradlew bootRun或者你可以使用构建JAR文件./gradlew build然后你可以运行JAR文件:

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

如果你正在使用Maven,你可以使用运行该应用程序./mvnw spring-boot:run或者您可以使用构建JAR文件./mvnw clean package然后你可以运行JAR文件:

java -jar target / gs-accessible-data-mysql-0.1.0.jar
上述过程将创建一个可运行的JAR。您也可以选择构建经典的WAR文件

记录输出显示。该服务应该在几秒钟内启动并运行。

测试应用程序

现在应用程序正在运行,您可以对其进行测试。

使用curl例如。现在您可以测试2个REST Web服务

localhost:8080/demo/all这将获得所有数据localhost:8080/demo/add这会将一个用户添加到数据中

$ curl 'localhost:8080/demo/add?name=First&email=someemail@someemailprovider.com'

答复应该是

Saved
$ curl 'localhost:8080/demo/all'

答复应该是

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

进行一些安全更改

现在,当您处于生产环境中时,您可能会遇到SQL注入攻击。黑客可能会注入DROP TABLE或任何其他破坏性的SQL命令。因此,作为安全实践,在将应用程序公开给用户之前,对数据库进行更改。

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

这会撤销与Spring应用程序关联的用户的所有特权。现在Spring应用程序不能在数据库中任何事情。我们不想那样,所以

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

这使你的Spring应用程序只有特权必要更改数据库,而不是结构(架构)的数据。

现在让这个改变到你的 src/main/resources/application.properties

spring.jpa.hibernate.ddl-auto=none

这不是create第一次运行Hibernate从你的实体创建表。

当您想对数据库进行更改时,请重新设置权限,将其更改spring.jpa.hibernate.ddl-autoupdate,然后重新运行应用程序,然后重复。或者,最好使用专用的迁移工具,如Flyway或Liquibase。

概要

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

也可以看看

以下指南也可能有所帮助:

想写一个新的指南或贡献一个现有的?查看我们的贡献指南

所有指南均附带代码的ASLv2许可证,以及用于撰写归属,NoDerivatives创意公共许可证
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值