How SpringBoot starts and initializes the execution of sql scripts
SpringBoot starts and initializes the execution of sql scripts
What if we want to execute some sql scripts when the project starts, SpringBoot provides us with With this function, you can execute the script when starting the SpringBoot project. Let's take a look.
Let’s take a look at the source code first
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
|
From the source code, we roughly know what it means. SpringBoot will find the script file from the class path by default, but Only script files with specified names of schema or schema-platform can be placed under the class path. If we want to divide multiple script files, then this method is not suitable, then we need to add them in application.properties or application.yml Go to the configuration script list. Can this initialization script operation be controlled in the configuration file? Yes, there is an initialization-mode attribute, which can be set to three values. Always means initialization is always performed, and embedded only initializes the memory database (default value) , such as h3, etc., never means no initialization is performed.
1 2 3 4 5 6 7 |
|
Let’s verify these two methods
1. Place the script file of schema or schema-platform by default
1 |
|
View The database does not have the department table. Next, we start the program
After starting, we take a look again and execute
2. Specify multiple sql scripts in the configuration file
1 2 3 4 5 6 7 8 9 10 11 |
|
The three sql scripts are all insert statements
1 2 3 |
|
There is no data in the table now. Next we start the program
#After starting, we take a look again and there are three pieces of data in the table
It is the steps for SpringBoot to start and initialize the sql script
The SpringBoot project executes the specified sql file at startup
1. Execute at startup
When the project is started, execute the specified file first When the SQL statement is required, you can add the SQL file that needs to be executed in the resources folder. The SQL statement in the file can be a DDL script or a DML script, and then add the corresponding configuration to the configuration, as follows:
1 2 3 |
|
2. Execute multiple sql files
spring.datasource.schema and spring.datasource.data both support receiving a list, so when you need to execute multiple sql files, you can use the following configuration:
1 2 3 |
|
3. Different running environments execute different scripts
Generally, there will be multiple running environments, such as development, testing, production, etc. The SQL that usually needs to be executed in different operating environments will be different. To solve this problem, wildcards can be used.
Create folders for different environments
Create folders corresponding to different environments in the resources folder, such as dev/, sit/, prod/.
Configuration
application.yml
1 2 3 4 |
|
Note: ${} wildcard supports default values. For example, ${spring.profiles.active:dev} in the above configuration, before the semicolon is to take the value of the attribute spring.profiles.active, and when the value of the attribute does not exist, the value after the semicolon is used, that is dev.
bootstrap.yml
1 2 3 |
|
Reminder: The spring.profiles.active property is generally configured in bootstrap.yml or bootstrap.properties.
4. Support different databases
Because the syntax of different databases is different, to achieve the same function, the SQL statements of different databases may be different, so there may be multiple copies. sql file. When you need to support different databases, you can use the following configuration:
1 2 3 4 5 |
|
Reminder: The default value of the platform attribute is 'all', so only use the above configuration when switching between different databases, because the default value In this case, spring boot will automatically detect the currently used database.
Note: At this time, taking the dev allowed environment as an example, the following files must exist in the resources/dev/ folder: schema-mysql.sql and data-mysql.sql.
5. Avoid Pitfalls
5.1 Pitfalls
When there are stored procedures or functions in the executed sql file, an error will be reported when starting the project .
For example, there is such a requirement now: when the project starts, scan a certain table. When the number of records in the table is 0, insert multiple records; when it is greater than 0, skip it.
The schema.sql file script is as follows:
1 2 3 4 5 6 |
|
Start the project and report an error for the following reasons:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'create procedure p1() begin declare row_num int' at line 1
大致的意思是:'create procedure p1() begin declare row_num int'这一句出现语法错误。刚看到这一句,我一开始是懵逼的,吓得我赶紧去比对mysql存储过程的写法,对了好久都发现没错,最后看到一篇讲解spring boot配置启动时执行sql脚本的文章,发现其中多了一项配置:spring.datasource.separator=$$。然后看源码发现,spring boot在解析sql脚本时,默认是以';'作为断句的分隔符的。看到这里,不难看出报错的原因,即:spring boot把'create procedure p1() begin declare row_num int'当成是一条普通的sql语句。而我们需要的是创建一个存储过程。
5.2 解决方案
修改sql脚本的断句分隔符。如:spring.datasource.separator=$$。然后把脚本改成:
1 2 3 4 5 6 |
|
5.3 不足
因为sql脚本的断句分隔符从';'变成'$$',所以可能需要在DDL、DML语句的';'后加'$$',不然可能会出现将整个脚本当成一条sql语句来执行的情况。比如:
1 2 3 4 5 6 7 8 |
|
The above is the detailed content of How SpringBoot starts and initializes the execution of sql scripts. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

"Usage of Division Operation in OracleSQL" In OracleSQL, division operation is one of the common mathematical operations. During data query and processing, division operations can help us calculate the ratio between fields or derive the logical relationship between specific values. This article will introduce the usage of division operation in OracleSQL and provide specific code examples. 1. Two ways of division operations in OracleSQL In OracleSQL, division operations can be performed in two different ways.

Oracle and DB2 are two commonly used relational database management systems, each of which has its own unique SQL syntax and characteristics. This article will compare and differ between the SQL syntax of Oracle and DB2, and provide specific code examples. Database connection In Oracle, use the following statement to connect to the database: CONNECTusername/password@database. In DB2, the statement to connect to the database is as follows: CONNECTTOdataba

What is Identity in SQL? Specific code examples are needed. In SQL, Identity is a special data type used to generate auto-incrementing numbers. It is often used to uniquely identify each row of data in a table. The Identity column is often used in conjunction with the primary key column to ensure that each record has a unique identifier. This article will detail how to use Identity and some practical code examples. The basic way to use Identity is to use Identit when creating a table.

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

Solution: 1. Check whether the logged-in user has sufficient permissions to access or operate the database, and ensure that the user has the correct permissions; 2. Check whether the account of the SQL Server service has permission to access the specified file or folder, and ensure that the account Have sufficient permissions to read and write the file or folder; 3. Check whether the specified database file has been opened or locked by other processes, try to close or release the file, and rerun the query; 4. Try as administrator Run Management Studio as etc.

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How to use SQL statements for data aggregation and statistics in MySQL? Data aggregation and statistics are very important steps when performing data analysis and statistics. As a powerful relational database management system, MySQL provides a wealth of aggregation and statistical functions, which can easily perform data aggregation and statistical operations. This article will introduce the method of using SQL statements to perform data aggregation and statistics in MySQL, and provide specific code examples. 1. Use the COUNT function for counting. The COUNT function is the most commonly used
