生成与 Hibernate 的“分配”一起使用的标识符发电机

发布于 12-18 01:16 字数 784 浏览 1 评论 0原文

我们告诉 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久而酒知2024-12-25 01:16:03

是的(见下文),但明显的问题是“为什么”?
为了达到相同的结果需要做大量的工作。

但是,如果您必须...
fictionalMethodThatGeneratesIdentifiers() 需要执行休眠序列生成器执行的操作,这可能是特定数据库获取下一个序列号所需的任何操作。

如果您这样做,请注意文档中的说明:

分配的生成器使 Hibernate 使用 unsaved-value="undefined"。
这迫使 Hibernate 访问数据库来确定是否存在
实例是瞬态的或分离的,除非有版本或
timestamp 属性,或者您定义 Interceptor.isUnsaved()。

因此,我建议显式地将未保存值映射到 -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:

The assigned generator makes Hibernate use unsaved-value="undefined".
This forces Hibernate to go to the database to determine if an
instance is transient or detached, unless there is a version or
timestamp property, or you define Interceptor.isUnsaved().

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文