休眠 ID 增量预言机 [英] hibernate ID increment oracle
问题描述
通过将其放入每个实体类,我设法让 hibernate 将每个表的 id 增加 1.
I managed to let hibernate increment the id of every table by 1 by putting this into every entity class.
@Entity
public class TestObject implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="idgen")
@SequenceGenerator(
name="idgen",
sequenceName="testobject_seq",
allocationSize=1,
initialValue=1
)
我有两个表,我通过 Oracle SQL Developer 手动填充数据.在我创建表之后.
I have two tables which i fill with data manually through the Oracle SQL Developer. After i created the tables.
<property name="hibernate.hbm2ddl.auto">create</property>
对于其中包含数据的 2 个表,我将 initialValue 设置为我需要的值.例如,表 testchamber 有 22 行数据.所以我的注释更改为:
For the 2 tables with data in it i set the initialValue to what i need. For instance, table testchamber has 22 rows with data. So my annotation changes to this:
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="idgen")
@SequenceGenerator(
name="idgen",
sequenceName="testchamber_seq",
allocationSize=1,
initialValue=23
)
但是当我尝试保存一个新的 testChamber 实体时,我收到了这个错误.
But when i try to save a new testChamber entity i get this error.
org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session
在更改注释之前,我可以毫无问题地保存我的实体,但是使用旧注释 hibernate 随机增加了 id.例如,hibernate 给了一个新实体 id 60、61 而不是 23、24 等等.
I could save my entity without a problem before i changed the annotation but with the old annotation hibernate incremented the id randomly. For instance, hibernate gave a new entity the id 60, 61 instead of 23, 24 and so on..
这是我的旧注释:
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
- 有没有一种正确的方法来告诉休眠一个表已经里面的数据,它应该从一个特定的数字开始计数?
- 或者我怎样才能摆脱NonUniqueObjectException".
推荐答案
这篇文章帮助我解决了我的问题链接".但是来自@nolexa 的 anser 是正确的,而不是来自 Alex Gitelman 的答案,后者实际上被检查为正确的.我把这个
This post helped me with my problem "link". But the anser from @nolexa is correct, not from Alex Gitelman which is actually checked as correct. I put this
<property name="hibernate.id.new_generator_mappings">true</property>
进入我的 hibernate.cfg.xml 文件,我创建的所有序列现在都可以正常工作.非常感谢@nolexa!!
into my hibernate.cfg.xml file and all my created sequences work fine now. Thank you very much @nolexa!!
这篇关于休眠 ID 增量预言机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!