使用Spring Boot访问MySQL数据库

本文详述了如何创建一个Spring Boot应用连接到MySQL数据库,包括构建Maven项目、配置数据库连接、创建@Entity模型、定义存储库接口、构建控制器及运行和测试应用程序的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简述

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

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

前提准备

  • MySQL版本5.6及以上版本。如果您已经安装了docker,那么可以将数据库作为一个容器运行。

  • JDK 1.8 及以上版本

  • Maven 3.0及以上版本

构建Maven项目

构建Spring的Maven项目基础框架

  Maven项目的文件结构:

└── src
    └── main
        └── java
            └── hello

  pom.xml源码:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-mysql-data</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- Use MySQL Connector-J -->

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  当然,该Maven项目的基础框架在Spring的GitHub官方账号中也有一份,我们可以直接将其下载下来直接使用。链接如下:

  这个 Spring Boot Maven插件提供了许多方便的特性

  • 它收集类路径上的所有jar,并构建一个单一的、可运行的“über-jar”,这使得执行和传输您的服务更加方便。

  • 它搜索public static void main()方法并将其标记为可运行的类。

  • 它提供了一个内置的依赖解析器,它可以设置版本号来匹配Spring Boot dependencies。您可以覆盖任何您希望的版本,但是它将引导默认所选择的版本集。

创建数据库

  创建数据库指令如下:

create database db_example;

创建application.properties文件

  Spring引导会给您提供所有的默认值,数据库中的默认值是H2,因此当您想要更改这个并使用任何其他数据库时,您必须定义application.properties文件中的连接属性。

  application.properties文件的存放位置:

src/main/resources/application.properties

  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根据给定的实体结构更改数据库。

  • create:每次都创建数据库,但不要在关闭时删除它。

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

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

  H2和其他嵌入式数据库的默认值是create-drop,但是对于MySQL这样的其他数据库来说,它是none

创建@ 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的名称与更改的名称相同,bean名称将是userRepository

创建控制器

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();
    }
}

  上面的例子没有显式地指定GETPUTPOST等等,因为@GetMapping@RequestMapping(method=GET)的一个快捷方式。@RequestMapping在默认情况下映射所有HTTP操作。使用@RequestMapping(method=GET)或其他快捷方式来缩小这个映射。

运行程序

使应用程序可执行文件

  尽管可以将此服务打包为用于部署到外部应用服务器的传统WAR文件,但下面演示的更简单的方法创建了一个独立的应用程序。您可以将所有内容打包到一个单独的、可执行的JAR文件中,这个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文件,该文件包含所有必需的依赖项、类和资源,并运行该文件。这使得在整个开发生命周期中,跨不同的环境,以及在不同的环境中,将服务作为一个独立的应用程序进行发布、版本和部署服务变得更加容易。

  在Maven中,如果是Linux操作系统,我们需要在应用程序下使用./mvnw spring-boot:run,如果是windows操作系统,我们需要在应用程序下使用mvnw spring-boot:run或者你可以在Linux下使用./mvnw clean package如果在windows下使用mvnw clean package。然后你就可以运行这个JAR文件了,运行指令如下:

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

  上面的过程将创建一个可运行的JAR。您也可以选择构建一个典型的WAR文件。

测试应用程序

  现在应用程序已经成功运行,我们可以使用curl的方式来进行测试。现在有2个REST Web服务可以测试。localhost:8080/demo/all用于获取所有的数据,localhost:8080/demo/add用于将user信息添加到数据库中。

  在浏览器地址栏中用于添加用户信息的url如下:

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

  它的响应是:

Saved

  访问保存的用户信息的地址如下:

localhost:8080/demo/all

  此时的响应信息是:

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

  一旦上面的程序运行一次后,相应的数据表就被生成了,此时我们就不用再更改数据表了,此时我们应该将application.properties中的spring.jpa.hibernate.ddl-auto更改为none

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值