将 Spring Boot 中的嵌入式数据库从 H2 更改为 MySQL

ele*_*lec 4 java mysql model-view-controller spring h2

有没有办法在几乎完成的应用程序中更改数据库?我遇到了许多在 MySQL 中没有发生的 H2 问题。例如 ALTER TABLE yourtable AUTO_INCREMENT = 1; 不起作用,相反,我不得不使用重启,它的效果不如 MySQL 版本。现在我也遇到了 datediff 问题。那么是否可以在正在进行的应用程序中更改数据库?

Gar*_*udo 7

是的你可以。在 pom 文件中包含 MySql 的依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

为扩展 JpaRepository 的 mysql 创建存储库接口:

public interface SqlDAO  extends JpaRepository<YourPOJO,Long>{
   // you can use JpaRepository methods out of the box or write custom ones
}
Run Code Online (Sandbox Code Playgroud)

为您的 sql 添加属性,您可以使用 .properties 或 .yml 文件。我使用 yaml:

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/coolDB
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
Run Code Online (Sandbox Code Playgroud)

不要忘记运行 MySql 数据库本身,你很高兴。您的服务现在应该使用您的存储库接口与 Sql 进行通信。

这是 Jpa 文档以及如何创建自定义方法的链接:https ://docs.spring.io/spring-data/jpa/docs/1.4.1.RELEASE/reference/html/jpa.repositories.html

编辑:您必须手动在 mysql 控制台中创建数据库,Spring 不会为您完成。您可以将 .sql 文件包含到您的资源目录中以创建虚拟数据或进一步设置 sql 设置,Spring 将为您运行该文件。