Spring Boot Database initialization MySQLException for Trigger

前端 未结 2 2104
别跟我提以往
别跟我提以往 2021-01-19 12:23

I am using Spring Boot Database initialization using Spring JDBC with schema.sql file.I am using MYSQL

If I have simple table creation in schema.sql as follows it wo

2条回答
  •  没有蜡笔的小新
    2021-01-19 12:53

    setting spring.datasource.separator=^; does not resolved my issue.

    I am using ResourceDatabasePopulator class to load sql scripts and found that this class provides method to set Separator so i did that.

    Note: dataSource object is autowired and is configured by spring. so add it (javax.sql.DataSource) before using it.

    @Autowired DataSoruce dataSource

    ResourceDatabasePopulator triggersPopulator = new ResourceDatabasePopulator(false, false, StandardCharsets.UTF_8.toString(), new ClassPathResource("triggers.sql"));
            triggersPopulator.setSeparator("//");
            triggersPopulator.execute(dataSource);
    

    and done changes in sql script as per separator (//).

    drop trigger if exists news_data_total_news_incremental_trigger;
    //
    create trigger news_data_total_news_incremental_trigger
    after insert on `news_data` for each row
    begin
    declare cnt,newcnt bigint;
    select `count` into cnt from `news_data_total_news` limit 1;
    set newcnt = cnt + 1;
    update `news_data_total_news` set `count` = newcnt where `count` = cnt;
    end//
    

    And it worked.

    One more thing, we can have multiple ResourceDatabasePopulator objects with different separator defined.

    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator(false, false, StandardCharsets.UTF_8.toString(), new ClassPathResource("data.sql"));
            resourceDatabasePopulator.execute(dataSource);
            
    ResourceDatabasePopulator triggersPopulator = new ResourceDatabasePopulator(false, false, StandardCharsets.UTF_8.toString(), new ClassPathResource("triggers.sql"));
            triggersPopulator.setSeparator("//");
            triggersPopulator.execute(dataSource);
    

    As you can see, i have two ResourceDatabasePopulator objects to load two different sql scripts, data.sql with default separator and triggers.sql with // as separator.

提交回复
热议问题