生成与 Hibernate 的“分配”一起使用的标识符发电机
我们告诉 Hibernate 如何使用
标签生成标识符。例如:
<generator class="sequence">
<param name="sequence">person_id_sequence</param>
</generator>
我希望使用
。根据文档:
已分配
让应用程序在调用 save() 之前为对象分配一个标识符。
有没有办法也配置一个序列
生成器,我可以用它来生成分配给我的对象的标识符?
这大致就是我想要做的:
Session session = ...;
// This will use the "sequence" generator:
Integer id = session.fictionalMethodThatGeneratesIdentifiers(Person.class);
Person person = new Person();
person.setId(id);
person.setName("Adam");
// This will use the "assigned" generator:
session.save(person);
We tell Hibernate how to generate identifiers using the <generator>
tag. For example:
<generator class="sequence">
<param name="sequence">person_id_sequence</param>
</generator>
I wish to use <generator class="assigned">
. As per the documentation:
assigned
lets the application assign an identifier to the object before save() is called.
Is there a way to also configure a sequence
generator that I can use to generate the identifiers that I will assign to my objects?
This is roughly what I wish to do:
Session session = ...;
// This will use the "sequence" generator:
Integer id = session.fictionalMethodThatGeneratesIdentifiers(Person.class);
Person person = new Person();
person.setId(id);
person.setName("Adam");
// This will use the "assigned" generator:
session.save(person);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

是的(见下文),但明显的问题是“为什么”?
为了达到相同的结果需要做大量的工作。
但是,如果您必须...
fictionalMethodThatGeneratesIdentifiers() 需要执行休眠序列生成器执行的操作,这可能是特定数据库获取下一个序列号所需的任何操作。
如果您这样做,请注意文档中的说明:
因此,我建议显式地将未保存值映射到 -1,并让您的对象将 id 值初始化为该值,否则每次尝试保存实例时您都会看到很多额外的开销。
Yes (see below), but the obvious question is "why"?
That's a lot of work just to arrive at the same result.
However, if you must...
fictionalMethodThatGeneratesIdentifiers() would need to do what the hibernate sequence generator does, which is presumably whatever is required of your particular database to get the next sequence number.
If you do this, note that the documentation says:
So, I'd suggest explicitly mapping unsaved-value to, say -1, and having your object initialize the id value to that, otherwise you are going to see a lot of extra overhead every time you try to save an instance.