我是Java Spring新手,我通过添加依赖项创建了默认项目,现在我希望在启动应用程序时创建Weather数据库,如果计算机上不存在的话。我使用的是mysql数据库。
- 我如何实现这一点,因为我得到的错误,当我启动应用程序?*
- 另一个问题:是否可以在不显式指定数据库中的用户名和密码的情况下实现这一点?*
java.sql.SQLSyntaxErrorException: Unknown database 'weather'
个字符
build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.0'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.mysql:mysql-connector-j'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
型
应用.属性
spring.datasource.url=jdbc:mysql://localhost:3306/weather?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.sql.init.mode=always
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
型
2条答案
按热度按时间cu6pst1q1#
一个好主意可能是使用测试容器。所有你需要做的就是运行docker。Springboot将处理其余的。它将自动创建并连接到数据库,而不需要知道用户名和密码。对于我的项目,我使用Postgres和MySql的设置是相同的。你需要安装它的依赖项。
字符串
我正在使用它进行测试,所以我通过执行以下操作来运行具有新数据库的应用程序:
型
iswrvxsc2#
试着看看flyway来处理你的数据库迁移。它是一个在启动时执行sql脚本的工具。
https://flywaydb.org/