I have a table and a generator in the database. This table has a primary key which is an Integer. If the user tries to insert records in the table, hibernate does a select from the sequence in the database, thus it makes the sequence to increase itself. The problem is, if some error occurs while committing the transaction, the sequence is already increased, and the next record to be saved won't have it's primary key with a consistent sequence comparing to the last record inserted before.
Is there a way to solve this?
-------- EDIT ---------
I managed to create a trigger that does this job:
CREATE TRIGGER TBLTESTE_BI0 FOR TBLTEST
ACTIVE BEFORE INSERT POSITION 0
AS
declare variable next_value integer;
begin
select coalesce(max(my_sequence_field+1),1) from tbltest into :next_value;
new.my_sequence_field=:next_value;
end
I'm not going to use this as the primary key of course, the primary key will still be generated by the sequence generator. But just a question, is it guaranteed that the my_sequence_field will have the correct sequence, with no repeated values? Consider that the value will be set only by the trigger.