简体   繁体   中英

Get Current User for Delete Trigger - Spring MyBatis - Liquibase

I have a Spring services project that uses MyBatis and Liquibase. I've made an audit table that has triggers for INSERT/UPDATE/DELETE.

With INSERT/UPDATE I'm already storing the user id so it's not a problem to do NEW.USER_ID, but with DELETE I only have OLD.USER_ID which obviously doesn't reflect the current user making the change.

Excluding some info, I have this in liquibase (putting *s around what should change):

    <sql endDelimiter="|">
        CREATE TRIGGER DELETE_TRIGGER
        AFTER DELETE
        ON TABLE_NAME
        FOR EACH ROW
        BEGIN
        INSERT INTO TABLE_NAME_A (CHANGE_TYPE, CHANGE_ID, CHANGE_DATE)
        VALUES ('DELETE', **OLD.USER_ID**, now());
        END;
        |
    </sql>

So I'm not sure what to replace OLD.UPDATE_ID with. The other examples I found often have to do with sql servers and mssql. So maybe I just failed as searching as I didn't find something that could work within spring/mybatis/liquibase/mysql.

Filling out how I solved this.

I changed the base trigger to be

<sql endDelimiter="|">
        CREATE TRIGGER DELETE_TRIGGER
        AFTER DELETE
        ON TABLE_NAME
        FOR EACH ROW
        BEGIN
        INSERT INTO TABLE_NAME_A (CHANGE_TYPE, CHANGE_ID, CHANGE_DATE)
        VALUES ('DELETE', user(), now());
        END;
        |
</sql>

So that it fills the user field with something. Then after the deletion I wrote another mapper to go in and update the ID field to the current user calling my service.

<update id="updateAuditTableChangeIdAfterDeletion">
    UPDATE TABLE_NAME_A
    SET CHANGE_ID = #{1}
    WHERE UNIQUE_IDENTIFIER = #{0}
      AND CHANGE_TYPE = 'DELETE'
</update>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM