休眠 ID 增量 oracle

hibernate ID increment oracle

我设法让 hibernate 将每个 table 的 id 增加 1,方法是将其放入每个实体 class。

@Entity
public class TestObject implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="idgen")
@SequenceGenerator(
        name="idgen",
        sequenceName="testobject_seq",
        allocationSize=1,
        initialValue=1
    )

我有两个 table 通过 Oracle SQL Developer 手动填充数据。在我创建 tables.

之后
<property name="hibernate.hbm2ddl.auto">create</property>

对于其中包含数据的 2 tables,我将 initialValue 设置为我需要的值。 例如,table testchamber 有 22 行数据。所以我的注释更改为:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="idgen")
@SequenceGenerator(
        name="idgen",
        sequenceName="testchamber_seq",
        allocationSize=1,
        initialValue=23
    )

但是当我尝试保存一个新的 testChamber 实体时,出现了这个错误。

org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session

我可以在更改注释之前毫无问题地保存我的实体,但是使用旧注释休眠会随机增加 id。例如,hibernate 给了一个新实体 id 60、61 而不是 23、24 等等..

这是我的旧注释:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)

这个 post 帮助我解决了我的问题“link"。 但是来自@nolexa 的回答是正确的,而不是来自 Alex Gitelman 的回答,后者实际上被检查为正确。 我把这个

<property name="hibernate.id.new_generator_mappings">true</property>

到我的 hibernate.cfg.xml 文件中,我创建的所有序列现在都可以正常工作。非常感谢@nolexa!!