我在使用JPA的Oracle中有自动增量ID的问题。如果我使用这样的序列:
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "customerSequence")
@SequenceGenerator(name = "customerSequence", sequenceName = "CUSTOMER_SEQ")
private int id;
// getters and setters
}
我必须一直使用序列。例如,如果DBA不使用它并在执行这样的INSERT时提供实际的id值:
INSERT INTO CUSTOMER (ID, NAME) VALUES (1, 'Paul');
INSERT INTO CUSTOMER (ID, NAME) VALUES (2, 'John');
INSERT INTO CUSTOMER (ID, NAME) VALUES (3, 'Mark');
// bunch of other statements like this
然后序列值保持为0.所以CUSTOMER_SEQ.NEXTVAL
返回实际已经在数据库中的1。
我需要获得灵活性的最佳方法。提供id时,序列应递增,以使数字不会发生冲突。
P.S。我尝试使用这样的触发器:
CREATE OR REPLACE
TRIGGER CUSTOMER_INSERT
BEFORE INSERT ON "CUSTOMER"
FOR EACH ROW
DECLARE
MAX_ID NUMBER;
CURRENT_SEQ_VAL NUMBER;
BEGIN
IF :NEW.ID IS NULL THEN
SELECT CUSTOMER_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL;
ELSE
SELECT GREATEST(NVL(MAX(ID), 0), :NEW.ID) INTO MAX_ID FROM "CUSTOMER";
SELECT CUSTOMER_SEQ.NEXTVAL INTO CURRENT_SEQ_VAL FROM DUAL;
WHILE CURRENT_SEQ_VAL < MAX_ID
LOOP
SELECT CUSTOMER_SEQ.NEXTVAL INTO CURRENT_SEQ_VAL FROM DUAL;
END LOOP;
END IF;
END;
当我使用原始SQL进行插入时,它工作正常,但是当我使用JPA时,有时候我会得到太大的id,有时会出现像这两样的奇怪错误:
ORA-04091: table CUSTOMER is mutating, trigger/function may not see it
ORA-04088: error during execution of trigger 'CUSTOMER_INSERT'
可能我在这里做错了什么。有人可以帮我找到解决方案吗?