Table of Contents
SpringBoot starts and initializes the execution of sql scripts
Let’s take a look at the source code first
Let’s verify these two methods
The SpringBoot project executes the specified sql file at startup
1. Execute at startup
2. Execute multiple sql files
3. Different running environments execute different scripts
4. Support different databases
5. Avoid Pitfalls
Home Java javaTutorial How SpringBoot starts and initializes the execution of sql scripts

How SpringBoot starts and initializes the execution of sql scripts

May 13, 2023 am 10:58 AM
sql springboot

    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

    How SpringBoot starts and initializes the execution of sql scripts

    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

    boolean createSchema() {

        //会从application.properties或application.yml中获取sql脚本列表

        List<Resource> scripts = this.getScripts("spring.datasource.schema", this.properties.getSchema(), "schema");

        if (!scripts.isEmpty()) {

            if (!this.isEnabled()) {

                logger.debug("Initialization disabled (not running DDL scripts)");

                return false;

            }

     

            String username = this.properties.getSchemaUsername();

            String password = this.properties.getSchemaPassword();

            //运行sql脚本

            this.runScripts(scripts, username, password);

        }

        return !scripts.isEmpty();

    }

    private List<Resource> getScripts(String propertyName, List<String> resources, String fallback) {

        if (resources != null) {

            //如果配置文件中配置,则加载配置文件

            return this.getResources(propertyName, resources, true);

        } else {

            //指定schema要使用的Platform(mysql、oracle),默认为all

            String platform = this.properties.getPlatform();

            List<String> fallbackResources = new ArrayList();

            //如果配置文件中没配置,则会去类路径下找名称为schema或schema-platform的文件

            fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");

            fallbackResources.add("classpath*:" + fallback + ".sql");

            return this.getResources(propertyName, fallbackResources, false);

        }

    }

    private List<Resource> getResources(String propertyName, List<String> locations, boolean validate) {

        List<Resource> resources = new ArrayList();

        Iterator var5 = locations.iterator();

     

        while(var5.hasNext()) {

            String location = (String)var5.next();

            Resource[] var7 = this.doGetResources(location);

            int var8 = var7.length;

     

            for(int var9 = 0; var9 < var8; ++var9) {

                Resource resource = var7[var9];

                //验证文件是否存在

                if (resource.exists()) {

                    resources.add(resource);

                } else if (validate) {

                    throw new InvalidConfigurationPropertyValueException(propertyName, resource, "The specified resource does not exist.");

                }

            }

        }

        return resources;

    }

    Copy after login

    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

    spring:

      datasource:

        username: root

        password: liuzhenyu199577

        url: jdbc:mysql://localhost:3306/jdbc

        driver-class-name: com.mysql.cj.jdbc.Driver

        initialization-mode: always

    Copy after login

    Let’s verify these two methods

    1. Place the script file of schema or schema-platform by default

    How SpringBoot starts and initializes the execution of sql scripts

    1

    CREATE TABLE IF NOT EXISTS department (ID VARCHAR(40) NOT NULL, NAME VARCHAR(100), PRIMARY KEY (ID));

    Copy after login

    View The database does not have the department table. Next, we start the program

    How SpringBoot starts and initializes the execution of sql scripts

    After starting, we take a look again and execute

    How SpringBoot starts and initializes the execution of sql scripts

    2. Specify multiple sql scripts in the configuration file

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    spring:

      datasource:

        username: root

        password: liuzhenyu199577

        url: jdbc:mysql://localhost:3306/jdbc

        driver-class-name: com.mysql.cj.jdbc.Driver

        initialization-mode: always

        schema:

          - classpath:department.sql

          - classpath:department2.sql

          - classpath:department3.sql

    Copy after login

    How SpringBoot starts and initializes the execution of sql scripts

    The three sql scripts are all insert statements

    1

    2

    3

    INSERT INTO department (ID,NAME) VALUES (&#39;1&#39;,&#39;2&#39;)

    INSERT INTO department (ID,NAME) VALUES (&#39;2&#39;,&#39;3&#39;)

    INSERT INTO department (ID,NAME) VALUES (&#39;3&#39;,&#39;4&#39;)

    Copy after login

    There is no data in the table now. Next we start the program

    How SpringBoot starts and initializes the execution of sql scripts

    #After starting, we take a look again and there are three pieces of data in the table

    How SpringBoot starts and initializes the execution of sql scripts

    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

    spring:

      datasource:

        schema: classpath:schema.sql # schema.sql中一般存放的是DDL脚本,即通常为创建或更新库表的脚本 data: classpath:data.sql # data.sql中一般是DML脚本,即通常为数据插入脚本

    Copy after login

    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

    spring:

      datasource:

        schema: classpath:schema_1.sql, classpath:schema_2.sql data: classpath:data_1.sql, classpath:data_2.sql 或 spring: datasource: schema: - classpath:schema_1.sql - classpath:schema_2.sql data: - classpath:data_1.sql - classpath:data_2.sql

    Copy after login

    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

    spring:

      datasource:

        schema: classpath:${spring.profiles.active:dev}/schema.sql

        data: classpath:${spring.profiles.active:dev}/data.sql

    Copy after login

    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

    spring:

      profiles:

        active: dev # dev/sit/prod等。分别对应开发、测试、生产等不同运行环境。

    Copy after login

    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

    spring:

      datasource:

        schema: classpath:${spring.profiles.active:dev}/schema-${spring.datasource.platform}.sql

        data: classpath:${spring.profiles.active:dev}/data-${spring.datasource.platform}.sql

        platform: mysql

    Copy after login

    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

    -- 当存储过程`p1`存在时,删除。

    drop procedure if exists p1;

      

    -- 创建存储过程`p1`

    create procedure p1()

    begin declare row_num int; select count(*) into row_num from `t_user`; if row_num = 0 then INSERT INTO `t_user`(`username`, `password`) VALUES (&#39;zhangsan&#39;, &#39;123456&#39;); end if; end; -- 调用存储过程`p1` call p1(); drop procedure if exists p1;

    Copy after login

    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

    -- 当存储过程`p1`存在时,删除。

    drop procedure if exists p1;$$

      

    -- 创建存储过程`p1`

    create procedure p1()

    begin declare row_num int; select count(*) into row_num from `t_user`; if row_num = 0 then INSERT INTO `t_user`(`username`, `password`) VALUES (&#39;zhangsan&#39;, &#39;123456&#39;); end if; end;$$ -- 调用存储过程`p1` call p1();$$ drop procedure if exists p1;$$

    Copy after login

    5.3 不足

    因为sql脚本的断句分隔符从';'变成'$$',所以可能需要在DDL、DML语句的';'后加'$$',不然可能会出现将整个脚本当成一条sql语句来执行的情况。比如:

    1

    2

    3

    4

    5

    6

    7

    8

    -- DDL

    CREATE TABLE `table_name` (

      -- 字段定义

      ...

    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;$$

      

    -- DML

    INSERT INTO `table_name` VALUE(...);$$

    Copy after login

    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!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

    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 Oracle SQL Usage of division operation in Oracle SQL Mar 10, 2024 pm 03:06 PM

    "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.

    Comparison and differences of SQL syntax between Oracle and DB2 Comparison and differences of SQL syntax between Oracle and DB2 Mar 11, 2024 pm 12:09 PM

    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 does the identity attribute in SQL mean? What does the identity attribute in SQL mean? Feb 19, 2024 am 11:24 AM

    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.

    Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

    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

    How to solve the 5120 error in SQL How to solve the 5120 error in SQL Mar 06, 2024 pm 04:33 PM

    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.

    Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

    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? How to use SQL statements for data aggregation and statistics in MySQL? Dec 17, 2023 am 08:41 AM

    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

    See all articles