简体   繁体   中英

Spring Boot not running schema.sql

I am having an issue running the schema.sql upon running the program.

In my pom.xml, I already have the mysql config:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

I only have one class

@SpringBootApplication
public class Application {...}

Under src/resources, I have schema.sql containing:

DROP TABLE IF EXISTS test_table;

CREATE TABLE test_table (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    ...
);

Under src/resources, I have application.yml containing:

spring.datasource.driverClassName: "com.mysql.jdbc.Driver"
spring.datasource.url: "jdbc:mysql://localhost:3306/sample?useSSL=false"
spring.datasource.username: "****"
spring.datasource.password: "****"

I have confirmed that I am able to connect to the database "sample" upon starting the application, however, it's not creating the table. Please advise.

在我的情况下(Spring Boot 2.0.0+),仅当属性设置spring.datasource.initialization-mode=alwaysspring.jpa.hibernate.ddl-auto=none结合使用时,它才能按预期工作。

That's because Spring Boot has check in DataSourceInitializer's initSchema() method.

在此处输入图片说明

It will execute scripts only if your database is of type H2,DERBY,HSQL

However, you can override this behaviour by using following setting in application.properties

spring.datasource.initialization-mode=always

DataSourceInitializer.java EmbeddedDatabaseConnection.java

From spring boot version 2.7 onward, this will work:

spring.sql.init.mode=always
spring.jpa.hibernate.ddl-auto=update

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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