spring Java Sping Boot 在应用程序启动时创建MySQL数据库

3zwtqj6y  于 2024-01-05  发布在  Spring
关注(0)|答案(2)|浏览(139)

我是Java Spring新手,我通过添加依赖项创建了默认项目,现在我希望在启动应用程序时创建Weather数据库,如果计算机上不存在的话。我使用的是mysql数据库。

  • 我如何实现这一点,因为我得到的错误,当我启动应用程序?*
  • 另一个问题:是否可以在不显式指定数据库中的用户名和密码的情况下实现这一点?*
  1. java.sql.SQLSyntaxErrorException: Unknown database 'weather'

个字符

build.gradle

  1. plugins {
  2. id 'java'
  3. id 'org.springframework.boot' version '3.2.0'
  4. id 'io.spring.dependency-management' version '1.1.4'
  5. }
  6. group = 'com.example'
  7. version = '0.0.1-SNAPSHOT'
  8. java {
  9. sourceCompatibility = '17'
  10. }
  11. repositories {
  12. mavenCentral()
  13. }
  14. dependencies {
  15. implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
  16. implementation 'org.springframework.boot:spring-boot-starter-web'
  17. developmentOnly 'org.springframework.boot:spring-boot-devtools'
  18. runtimeOnly 'com.mysql:mysql-connector-j'
  19. testImplementation 'org.springframework.boot:spring-boot-starter-test'
  20. }
  21. tasks.named('test') {
  22. useJUnitPlatform()
  23. }

应用.属性

  1. spring.datasource.url=jdbc:mysql://localhost:3306/weather?useSSL=false&serverTimezone=UTC
  2. spring.datasource.username=root
  3. spring.datasource.password=password
  4. spring.sql.init.mode=always
  5. spring.jpa.hibernate.ddl-auto=update
  6. spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

cu6pst1q

cu6pst1q1#

一个好主意可能是使用测试容器。所有你需要做的就是运行docker。Springboot将处理其余的。它将自动创建并连接到数据库,而不需要知道用户名和密码。对于我的项目,我使用Postgres和MySql的设置是相同的。你需要安装它的依赖项。

  1. @TestConfiguration(proxyBeanMethods = false)
  2. public class TestContainersConfig {
  3. @Bean
  4. @ServiceConnection
  5. PostgreSQLContainer<?> postgreSQLContainer() {
  6. return new PostgreSQLContainer<>("postgres:15");
  7. }
  8. }

字符串
我正在使用它进行测试,所以我通过执行以下操作来运行具有新数据库的应用程序:

  1. public class TestEchoBoardApplication {
  2. public static void main(String[] args) {
  3. SpringApplication.from(EchoBoardApplication::main)
  4. .with(TestContainersConfig.class)
  5. .run(args);
  6. }
  7. }

展开查看全部
iswrvxsc

iswrvxsc2#

试着看看flyway来处理你的数据库迁移。它是一个在启动时执行sql脚本的工具。
https://flywaydb.org/

相关问题