You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Spring Boot启动时执行SQL脚本初始化MySQL失败问题咨询

Fixing SQL Script Execution on Spring Boot Startup (Without JPA)

Hey there! Let's troubleshoot why your SQL scripts aren't running when your Spring Boot app starts up, especially since you're skipping JPA. Here are the key checks and fixes to get this working:

1. Add the JDBC Starter Dependency

The spring.sql.init features rely on Spring's JDBC support, which isn't included in the web starter alone. Since you're not using JPA, you need to explicitly add the spring-boot-starter-jdbc dependency to your pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Without this, Spring Boot doesn't have the necessary components to execute your SQL scripts on startup.

2. Verify Script Location & Naming

Double-check that your schema-mysql.sql and data-mysql.sql files are placed directly in the src/main/resources directory. Spring Boot looks for scripts here by default when you set spring.sql.init.platform=mysql. Also, make sure there are no typos in the filenames (case sensitivity can matter on some operating systems, so stick to lowercase as you have).

3. Ensure the Target Database Exists

Your datasource URL points to MyDB, but Spring Boot's sql.init won't create the database itself—you need to manually create it in MySQL first. If MyDB doesn't exist, the script execution will fail silently (or throw a connection error in logs) because the app can't connect to a non-existent database.

4. Check Script Syntax (Minor But Important)

Looking at your data-mysql.sql, you're inserting an integer 100 into a VARCHAR(25) column. While MySQL will usually auto-convert this, it's better practice to wrap string values in quotes to avoid any unexpected issues:

INSERT INTO test_db(value) VALUES('100');

5. Inspect Startup Logs for Clues

Enable debug logging (or just check the standard logs) to see what's happening with script execution. Look for lines like:

  • Executing SQL script from classpath resource [schema-mysql.sql]
  • Executing SQL script from classpath resource [data-mysql.sql]
    If you don't see these, it means Spring isn't picking up the scripts. If you see error messages, they'll point you to the root cause (e.g., connection issues, invalid SQL syntax).

After making these changes, restart your app—your tables should be created and data inserted as expected!

内容的提问来源于stack exchange,提问作者Kylie

火山引擎 最新活动