gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:07:22 25 4
gpt4 key购买 nike

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

最佳答案

是的,你可以。在您的 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>

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

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

为您的 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

不要忘记运行 MySql 数据库本身,一切顺利。您的服务现在应该使用您的存储库接口(interface)与 Sql 进行通信。

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

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

关于java - 将 Spring Boot 中的嵌入式数据库从 H2 更改为 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45488742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com