我已经将我的课程映射为以下(省略其他字段仅作为ID事项):
@Entity
@Table(name = "MODEL_GROUP")
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class SettlementModelGroup implements Serializable
{
@Id
@GeneratedValue(generator = "MODEL_GROUP_SEQ", strategy = GenerationType.SEQUENCE)
@GenericGenerator(name = "MODEL_GROUP_SEQ",
strategy = "sequence",
parameters = @Parameter(name = "sequence", value = "SEQ_MODEL_GROUP_MODEL_GROUP_ID"))
@Column(name = "MODEL_GROUP_ID", nullable = false)
private Integer modelId;
}
当我保存新对象时:
Integer modelGroupId = sessionFactory.getCurrentSession().save( modelGroup );
System.out.println( modelGroupId );
ID设置为例如23
,但是当我查看数据库时,它实际上是24
。这导致了许多问题,因为我稍后使用此ID。不知道为什么会出现这个差距?
SQL日志显示一切正常(我这么认为):
Hibernate:
select
SEQ_MODEL_GROUP_MODEL_GROUP_ID.nextval
from
dual
Hibernate:
insert
into
MODEL_GROUP
(DOMAIN_ID, DESCRIPTION, NAME, PERIOD_TYPE_ID, MODEL_GROUP_TYPE_ID, STATUS_ID, OWNER_ID, MODEL_GROUP_ID)
values
(?, ?, ?, ?, ?, ?, ?, ?)
触发和序列:
CREATE SEQUENCE "SEQ_MODEL_GROUP_MODEL_GROUP_ID"
INCREMENT BY 1
START WITH 1
NOMAXVALUE
MINVALUE 1
NOCYCLE
NOCACHE
NOORDER
;
CREATE OR REPLACE TRIGGER "TRG_MODEL_GROUP_MODEL_GROUP_ID"
BEFORE INSERT
ON "MODEL_GROUP"
FOR EACH ROW
WHEN (NEW."MODEL_GROUP_ID" is NULL)
BEGIN
SELECT "SEQ_MODEL_GROUP_MODEL_GROUP_ID".NEXTVAL
INTO :NEW."MODEL_GROUP_ID"
FROM DUAL;
END;
答案 0 :(得分:1)
显然,当Hibernate向您的数据库询问ID的nextValue时,它也会触发Trigger。因此,当我要求ID时,我得到了数字23
但是当通过提交事务实际保存到数据库时,它再次增加,所以我得到了24
。解决方案如下所述:
HIbernate issue with Oracle Trigger for generating id from a sequence
为了使其正常工作,我更改了Trigger:
CREATE OR REPLACE TRIGGER "TRG_MODEL_GROUP_MODEL_GROUP_ID"
BEFORE INSERT
ON "MODEL_GROUP"
FOR EACH ROW
WHEN (NEW."MODEL_GROUP_ID" is NULL)
BEGIN
SELECT "SEQ_MODEL_GROUP_MODEL_GROUP_ID".NEXTVAL
INTO :NEW."MODEL_GROUP_ID"
FROM DUAL;
END;