Search code examples
javamysqlspring-bootsql-scripts

Spring Boot Database initialization MySQLException for Trigger


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 works fine

CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

But when I add one trigger as follows which runs correctly in MySQL Workbench

DROP TRIGGER IF EXISTS Persons_log_update; 

CREATE TRIGGER Persons_log_update 
    BEFORE UPDATE ON Persons
    FOR EACH ROW 
BEGIN

    INSERT INTO Personshistory(PersonID,LastName,FirstName,Address,City)
    values(OLD.PersonID,OLD.LastName,OLD.FirstName,OLD.Address,OLD.City);

END ^;

I have used spring.datasource.separator=^; in properties file as mentioned here

But it fails with exception as

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 TRIGGER Persons_log_update BEFORE UPDATE ON Persons FOR EACH ROW BE' at line 1

I guess my problem is same as this question but that is in postgresql.

Edit: If I remove spring.datasource.separator=^; from properties file and have below cursor

DROP TRIGGER IF EXISTS Persons_log_update; 

DELIMITER $$
CREATE TRIGGER Persons_log_update 
    BEFORE UPDATE ON Persons
    FOR EACH ROW 
BEGIN

    INSERT INTO Personshistory(PersonID,LastName,FirstName,Address,City)
    values(OLD.PersonID,OLD.LastName,OLD.FirstName,OLD.Address,OLD.City);

END$$
DELIMITER ;

It gives same error

 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 'DELIMITER $$ CREATE TRIGGER Persons_log_update BEFORE UPDATE ON Persons FO' at line 1

Solution

  • My issue was resolved when I have added spring.datasource.separator=^; in application.properties and every line out side the procedure/trigger should be terminated with ^; Example as follows:

    DROP TRIGGER IF EXISTS Persons_log_update ^; 
    
    CREATE TRIGGER Persons_log_update 
        BEFORE UPDATE ON Persons
        FOR EACH ROW 
    BEGIN
    
        INSERT INTO Personshistory(PersonID,LastName,FirstName,Address,City)
        values(OLD.PersonID,OLD.LastName,OLD.FirstName,OLD.Address,OLD.City);
    
    END ^;