Handling the concurrent request while persisting in oracle database?

后端 未结 4 992
孤独总比滥情好
孤独总比滥情好 2020-12-02 01:23

I have this scenario ,on a airline website (using Java) two separate customers send two requests at same time to book a same seat in same airline
from New York to Chica

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 01:42

    To handle concurrency in a web site a common practice it to have a column on each record that allows you to check it has not been updated since you got it. Either last update date or a sequential version number (auto incremented by a trigger).

    Typically you will read the data (plus the concurrency column)

    SELECT seat,etc,version_no
    FROM t1
    WHERE column = a_value
    

    Then when the user eventually gets round to booking the seat the update will work unless there has been an update.

    (the version number or update date will change after every update)

    BEGIN
        UPDATE t1
        SET seatTaken = true
        WHERE seatid = .....
        AND version_no = p_version
        RETURNING version_no INTO p_version;
    EXCEPTION WHEN NOT_FOUND THEN
        --Generate a custom exception 
        --concurrency viloation the record has been updated already
    END;
    

    the trigger to auto update the version number would look a little like this

    CREATE OR REPLACE TRIGGER t1_version
    AFTER INSERT OR UPDATE ON t1
    FOR EACH ROW
    BEGIN
        IF :new.version_no IS NULL THEN
           :new.version_no  := 0;
        ELSE
           :new.version_no  := :old.version_no  + 1;
        END IF;
    END;
    

提交回复
热议问题