简体   繁体   English

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

[英]Changing embedded database in Spring Boot from H2 to MySQL

Is there a way to change database in application that is almost done? 有没有办法在应用程序中更改几乎完成的数据库? I am encoutering many problems with H2 that does not occur in MySQL. 我在H2中遇到很多问题,而这些问题并没有发生在MySQL中。 For example ALTER TABLE yourtable AUTO_INCREMENT = 1; 例如ALTER TABLE yourtable AUTO_INCREMENT = 1; does not work and instead I had to use restart at which does not work as good as MySQL version. 不起作用,而我不得不使用重启,其中不如MySQL版本。 Also now I am having problems with datediff. 现在我也遇到了约会问题。 So is it possible to change database in ongoing application? 那么可以在正在进行的应用程序中更改数据库吗?

Yes you can. 是的你可以。 Include dependencies for MySql in your pom file: 在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>

Create your repository interface for mysql that extends JpaRepository: 为扩展JpaRepository的mysql创建存储库接口:

public interface SqlDAO  extends JpaRepository<YourPOJO,Long>{
   // you can use JpaRepository methods out of the box or write custom ones
}

Add properties for your sql, you can use .properties or .yml files. 添加sql的属性,可以使用.properties或.yml文件。 I use yaml: 我用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

Don't forget to run MySql database itself and you good to go. 不要忘记运行MySql数据库本身就好了。 Your Service now should be using your repository interface to communicate with Sql. 您的服务现在应该使用您的存储库接口与Sql通信。

Here is a link for Jpa documentation and how to create your custom methods: https://docs.spring.io/spring-data/jpa/docs/1.4.1.RELEASE/reference/html/jpa.repositories.html 以下是Jpa文档的链接以及如何创建自定义方法: https ://docs.spring.io/spring-data/jpa/docs/1.4.1.RELEASE/reference/html/jpa.repositories.html

Edit: you have to create database in mysql console manually, Spring won't do it for you. 编辑:你必须手动在mysql控制台中创建数据库,Spring不会为你做。 You can include .sql file into your resource directory to create dummy data or set sql settings further on, Spring will run that for you. 您可以将.sql文件包含到您的资源目录中以创建虚拟数据或进一步设置SQL设置,Spring将为您运行该文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM