Spring Boot中配置MySQL

x33g5p2x  于2022-10-06 转载在 Spring  
字(6.6k)|赞(0)|评价(0)|浏览(569)

在本教程中,我们将学习如何使用 Spring Boot CLI 和 MySQL 作为数据库来创建基本应用程序。然后,我们将应用程序导入 IDE 以创建一个示例应用程序,该应用程序存储一些数据,这些数据稍后由 SpringApplication 类检索。

我们将从 Spring 命令行界面开始。但是,如果您愿意,可以浏览 Spring Initializr Web 应用程序。
我们的 Web 应用程序,名为 samplewebapp,将需要 spring init 指定的以下依赖项:

$ spring init -d=web,jpa,mysql -n=jpa-demo.mysql jpa-demo-mysql

如您所见,为了在您的项目中包含 mysql 依赖项,将“mysql”传递给“-d”(依赖项)就足够了,您的 pom.xml 中将包含依赖项

现在让我们检查一下为我们创建了什么:

jpa-demo-mysql/
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── example
    │   │           └── jpademomysql
    │   │               └── Application.java
    │   └── resources
    │       ├── application.properties
    │       ├── static
    │       └── templates
    └── test
        └── java
            └── com
                └── example
                    └── jpademomysql
                        └── ApplicationTests.java

这是我们的 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.example</groupId>
    	
   <artifactId>jpa-demo-mysql</artifactId>
    	
   <version>0.0.1-SNAPSHOT</version>
    	
   <packaging>jar</packaging>
     	
   <name>jpa-demo.mysql</name>
    	
   <description>Demo project for Spring Boot</description>
     	
   <parent>
       		
      <groupId>org.springframework.boot</groupId>
       		
      <artifactId>spring-boot-starter-parent</artifactId>
       		
      <version>2.1.0.RELEASE</version>
       		
      <relativePath/>
       
      <!-- lookup parent from repository -->
       	
   </parent>
     	
   <properties>
       		
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       		
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
       		
      <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>

接下来要做的是在文件 application.properties 中包含数据库 JDBC 设置:

spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/mysqltutorial?useSSL=false spring.datasource.username=root spring.datasource.password= spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

事实上,应用程序不会做太多事情,所以让我们在名为 Person 的项目中添加一个 Entity

package com.example.samplewebapp;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Person {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  Long id;

  String name;
  String surname;

  public Person(String name, String surname) {
    super();
    this.name = name;
    this.surname = surname;
  }

  public Person() {
    super();
  }

  public Long getId() {
    return id;
  }

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

  public String getName() {
    return name;
  }

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

  public String getSurname() {
    return surname;
  }

  public void setSurname(String surname) {
    this.surname = surname;
  }

  @Override
  public String toString() {
    return "Person [id=" + id + ", name=" + name + ", surname=" + surname + "]";
  }
}

Spring 最酷的特性之一是能够在运行时从存储库接口自动创建存储库实现。开箱即用的存储库接口已经包含通过 id 查找实体和 findAll 实体的方法。我们将再添加一个名为“findBySurname”的方法,该方法在以下 PersonRepository 接口中定义:

package com.example.samplewebapp;

import java.util.List;
import org.springframework.data.repository.CrudRepository;

public interface PersonRepository extends CrudRepository<Person, Long> {
  List<Person> findBySurname(String surname);
}

我们完成了后端。现在我们将在@SpringBootApplication 类中添加一些逻辑来插入一些实体对象并使用存储库接口检索它们:

package com.example.samplewebapp;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SpringBootApplication public class DemoApplication {
  private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
  @Bean public CommandLineRunner demo(PersonRepository repository) {
    return (args) -> {
      // save a couple of persons
      repository.save(new Person("Jack", "Smith"));repository.save(new Person("Joe", "Black"));repository.save(new Person("Martin", "Bauer"));
      // fetch all persons
      log.info("Persons found with findAll():");log.info("-------------------------------");
      for (Person person: repository.findAll()) {
        log.info(person.toString());
      }
      log.info("");
      // fetch an individual person by ID
      repository.findById(1 L).ifPresent(person -> {
        log.info("Person found with findById(1L):");log.info("--------------------------------");log.info(person.toString());log.info("");
      });
      // fetch persons by last name 
      log.info("Person found with findBySurname('Black'):");log.info("--------------------------------------------");repository.findBySurname("Black").forEach(smith -> {
        log.info(smith.toString());
      });log.info("");
    };
  }
}

如您所见,我们使用了 CommandLineRunner 接口来运行演示。事实上,Spring Boot 提供了两个接口,CommandLineRunnerApplicationRunner 在应用程序启动时运行特定的代码片段。一旦 SpringApplication 完成,这些接口就会在 run() 之前被调用。
在我们的示例中使用的 CommandLineRunner 以字符串数组的形式提供对应用程序参数的访问。
您可以直接从您的工具运行应用程序,例如,如果您使用带有 Spring Tools 的 Eclipse,右键单击 DemoApplication 类并选择 Run As > SpringBoot app

作为替代方案,只需运行:

mvn clean install

或者

java -jar target/samplewebapp-0.0.1-SNAPSHOT.jar

这是 SpringApplication 类提供的输出:

Persons found with findAll():
-------------------------------

Person [id=1, name=Jack, surname=Smith]
Person [id=2, name=Joe, surname=Black]
Person [id=3, name=Martin, surname=Bauer]

Person found with findById(1L):
--------------------------------
Person [id=1, name=Jack, surname=Smith]

Person found with findBySurname('Black'):
--------------------------------------------
Person [id=2, name=Joe, surname=Black]

在本教程中,我们学习了如何使用 Spring Boot API 和 javax.persistence API 开发一个基本应用程序来存储一些数据并使用存储库类来检索它们。

相关文章

微信公众号

最新文章

更多