Spring Boot MySQL Tutorial

这些年来 2020-06-09

Spring is a popular Java application framework for creating enterprise applications. Spring Boot is an evolution of Spring framework which helps create stand-alone, production-grade Spring based applications with minimal effort.

Spring是用于创建企业应用程序的流行Java应用程序框架。Spring Boot是Spring框架的演进,可帮助您轻松创建独立的,生产级别的基于Spring的应用程序

MySQL (8.0+)

$ sudo service mysql start
$ sudo service mysql stop

These two commands are used to start and stop MySQL.

$ sudo service mysql status

We check the status of the database with service mysql status command.

$ mysql -u root -p

Now we need to reset the root password. We start the mysql command line tool. (The server must be running.) We connect as root.

mysql> SET PASSWORD = PASSWORD(‘newpassowrd‘);

We set a new password for root.

$ mysql_secure_installation

We can use mysql_secure_installation to increase security of MySQL server. We are given the choice to improve the MySQL root password, remove anonymous user accounts, disable root logins outside of localhost, and remove test databases.

可以使用mysql_secure_installation来提高MySQL服务器的安全性。我们也可以选择改进MySQL的root密码,删除匿名用户帐户,禁用localhost外部的root登录以及删除测试数据库。

mysql> CREATE DATABASE testdb;

We create a new testdb database.

mysql> CREATE USER  IDENTIFIED BY ‘s$cret‘;
mysql> GRANT ALL ON testdb.* TO ;

We create a new MySQL user and grant it privileges to the testdb database.

Creating MySQL table

Now we are going to create a new MySQL table called cities.

cities_mysql.sql

DROP TABLE IF EXISTS cities;
CREATE TABLE cities(id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100), population INT);

INSERT INTO cities(name, population) VALUES(‘Bratislava‘, 432000);
INSERT INTO cities(name, population) VALUES(‘Budapest‘, 1759000);
INSERT INTO cities(name, population) VALUES(‘Prague‘, 1280000);
INSERT INTO cities(name, population) VALUES(‘Warsaw‘, 1748000);
INSERT INTO cities(name, population) VALUES(‘Los Angeles‘, 3971000);
INSERT INTO cities(name, population) VALUES(‘New York‘, 8550000);
INSERT INTO cities(name, population) VALUES(‘Edinburgh‘, 464000);
INSERT INTO cities(name, population) VALUES(‘Berlin‘, 3671000);

This is SQL to create the cities table.

mysql> use testdb;
mysql> source cities_mysql.sql

With the source command, we execute the SQL statements.

Spring Boot MySQL example

The following application is a simple Spring Boot web application, which uses MySQL database. We have a home page with a link to display data from a database table. We use Freemarker templating system to join data with HTML.

以下应用程序是一个简单的Spring Boot Web应用程序,它使用MySQL数据库。有一个主页并带有一个链接,用于显示数据库表中的数据。使用Freemarker模板系统将数据与HTML连接

pom.xml
src
└── main
    ├── java
    │   └── com
    │       └── zetcode
    │           ├── Application.java
    │           ├── model
    │           │   └── City.java
    │           ├── controller
    │           │   └── MyController.java
    │           ├── repository
    │           │   └── CityRepository.java
    │           └── service
    │               ├── CityService.java
    │               └── ICityService.java
    └── resources
        ├── application.properties
        ├── static
        │   └── index.html
        └── templates
            └── showCities.ftlh

This is the project structure.

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>com.zetcode</groupId>
    <artifactId>springbootmysqlex</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>

        <!-- <java.version>11</java.version> -->
    </properties>

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

    <dependencies>
        <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>
            <!-- <scope>8.0.20</scope> -->
        </dependency>

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

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

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

</project>

Spring Boot starters are a set of convenient dependency descriptors which greatly simplify Maven configuration. The spring-boot-starter-parent has some common configurations for a Spring Boot application. The spring-boot-starter-web is a starter for building web, including RESTful, applications using Spring MVC. The spring-boot-starter-freemarker is a starter for building MVC web applications using Freemarker views. The spring-boot-starter-data-jpa is a starter for using Spring Data JPA with Hibernate.

Spring Boot启动器是一组方便的依赖项描述符,可以极大地简化Maven配置。spring-boot-starter-parent具有Spring Boot应用程序的一些常用配置。spring-boot-starter-web是使用Spring MVC构建Web(包括RESTful)应用程序的启动器。spring-boot-starter-freemarker是使用Freemarker视图构建MVC Web应用程序的启动器。spring-boot-starter-data-jpa是将Spring Data JPA与Hibernate结合使用的启动器。

The mysql-connector-java dependency is for the MySQL database driver.

mysql-connector-java依赖项用于MySQL数据库驱动程序。

The spring-boot-maven-plugin provides Spring Boot support in Maven, allowing us to package executable JAR or WAR archives. Its spring-boot:run goal runs the Spring Boot application.

spring-boot-maven-plugin在Maven中提供了Spring Boot支持,从而使我们可以打包可执行JAR或WAR档案。它的spring-boot:run目标运行Spring Boot应用程序。

resources/application.properties

spring.main.banner-mode=off
logging.level.org.springframework=ERROR

spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC
spring.datasource.username=user12
spring.datasource.password=s$cret

In the application.properties file we write various configuration settings of a Spring Boot application. With the spring.main.banner-mode property we turn off the Spring banner. With the logging.level.org.springframework we set the logging level for spring framework to ERROR. In the spring datasource properties we set up the MySQL datasource.

在application.properties文件中,编写了Spring Boot应用程序的各种配置设置。使用spring.main.banner-mode属性,可以关闭Spring banner 通过logging.level.org.springframework将spring框架的日志记录级别设置为ERROR 在spring数据源属性中,设置MySQL数据源

com/zetcode/model/City.java

package com.zetcode.model;

import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "cities")
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private int population;

    public City() {
    }

    public City(Long id, String name, int population) {
        this.id = id;
        this.name = name;
        this.population = population;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 79 * hash + Objects.hashCode(this.id);
        hash = 79 * hash + Objects.hashCode(this.name);
        hash = 79 * hash + this.population;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final City other = (City) obj;
        if (this.population != other.population) {
            return false;
        }
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        return Objects.equals(this.id, other.id);
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("City{");
        sb.append("id=").append(id);
        sb.append(", name=‘").append(name).append(‘\‘‘);
        sb.append(", population=").append(population);
        sb.append(‘}‘);
        return sb.toString();
    }
}

This is the City entity. Each entity must have at least two annotations defined: @Entity and @Id.

@Entity
@Table(name = "cities")
public class City {

The @Entity annotation specifies that the class is an entity and is mapped to a database table while the @Table annotation specifies the name of the database table to be used for mapping.

@Entity注解指定该类是一个实体,并映射到数据库表,而@Table注解指定用于映射的数据库表的名称

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

The primary key of an entity is specified with the @Id annotation. The @GeneratedValue gives a strategy for generating the values of primary keys.

实体的主键由@Id注解指定@GeneratedValue提供了一种用于生成主键值的策略

com/zetcode/repository/CityRepository.java

package com.zetcode.repository;

import com.zetcode.model.City;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CityRepository extends CrudRepository<City, Long> {

}

By extending from the Spring CrudRepository, we will have some methods for our data repository implemented, including findAll(). This way we save a lot of boilerplate code.

通过从Spring CrudRepository扩展,将实现一些用于数据存储库的方法,包括findAll() 这样,我们节省了大量样板代码

com/zetcode/service/ICityService.java

package com.zetcode.service;

import com.zetcode.model.City;
import java.util.List;

public interface ICityService {

    List<City> findAll();
}

ICityService provides the findAll() contract method declaration to get all cities from the data source.

ICityService提供了findAll()契约方法声明,以从数据源获取所有城市

com/zetcode/service/CityService.java

package com.zetcode.service;

import com.zetcode.model.City;
import com.zetcode.repository.CityRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CityService implements ICityService {

    @Autowired
    private CityRepository repository;

    @Override
    public List<City> findAll() {

        return (List<City>) repository.findAll();
    }
}

CityService contains the implementation of the findAll() method. We use the repository to retrieve data from the database.

CityService包含findAll()方法的实现。我们使用存储库从数据库检索数据

@Autowired
private CityRepository repository;

CityRepository is injected.

return (List<City>) repository.findAll();

The findAll() method of the repository returns the list of cities.

com/zetcode/controller/MyController.java

package com.zetcode.controller;

import com.zetcode.model.City;
import com.zetcode.service.ICityService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {

    @Autowired
    private ICityService cityService;

    @GetMapping("/showCities")
    public String findCities(Model model) {

        var cities = (List<City>) cityService.findAll();

        model.addAttribute("cities", cities);

        return "showCities";
    }
}

MyController class is annotated with @Controller.

@Autowired
private ICityService cityService;

We inject an ICityService into the countryService field.

@GetMapping("/showCities")
public String findCities(Model model) {

    var cities = (List<City>) cityService.findAll();

    model.addAttribute("cities", cities);

    return "showCities";
}

We map a request with the /showCities path to the controller‘s findCities() method. The @GetMapping annotation maps a GET request to the method. The model gains a list of cities and the processing is sent to the showCities.ftlh Freemarker template file.

我们将带有/showCities路径的请求映射到控制器的findCities()方法中@GetMapping注解将GET请求映射到该方法。该模型将获取城市列表,并将处理过程发送到showCities.ftlh Freemarker模板文件

resources/templates/showCities.ftlh

<!DOCTYPE html>
<html>
    <head>
        <title>Cities</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
    <body>
        <h2>List of cities</h2>

        <table>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Population</th>
            </tr>

            <#list cities as city>
                <tr>
                    <td>${city.id}</td>
                    <td>${city.name}</td>
                    <td>${city.population}</td>
                </tr>
            </#list>
        </table>
    </body>
</html>

In the showCities.ftlh template file, we display the data in an HTML table.

resources/static/index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>
        <a href="showCities">Show cities</a>
    </body>
</html>

In the index.html there is a link to show all cities.

com/zetcode/Application.java

package com.zetcode;

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

The Application sets up the Spring Boot application. The @SpringBootApplication enables auto-configuration and component scanning.

@SpringBootApplication启用自动配置和组件扫描

$ mvn spring-boot:run

After the application is run, we can navigate to localhost:8080.

In this tutorial, we have showed how to use MySQL database in a Spring Boot application.

相关推荐