2

我已经将我的班级映射如下(省略了其他字段,因为只有 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;
4

1 回答 1

1

显然,当 Hibernate 向数据库询问 ID 的 nextValue 时,它​​也会触发 Trigger。因此,当我询问 ID 时,我得到了数字23,但是当通过提交事务实际保存到数据库时,它又增加了,所以我得到了24. 解决方案在这里描述:

用于从序列生成 id 的 Oracle 触发器的 HIbernate 问题

为了使其正常工作,我更改了触发器:

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;
于 2012-07-27T21:21:03.670 回答