获取cascade=“all”中子级的ID关系,同时将其添加到集合中,在 Hibernate 中

发布于 2024-08-27 13:04:11 字数 453 浏览 6 评论 0原文

我有两个实体“父”和“子”,它们通过双向一对多关系链接,级联属性设置为“全部”。 使用下面的代码将子对象添加到父子集合时,在提交事务之前我无法获取持久化子实体的 ID:

Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
// "c" hasn't an ID (is always zero) 

但是,当我通过显式调用 session.save() 方法来持久化子实体时,即使事务尚未提交,ID也会立即创建并设置:

Child c = new Child();
session.save(c);
// "c" has an ID

有没有办法立即获取子实体的ID而不调用session.save()方法?

谢谢

i have two Entities, "Parent" and "Child", that are linked through a bidirectional one-to-many relationship with the cascade attribute set to "all".
When adding a Child object to the Parent children collection using the code below, i can't get the ID of the persisted child until i commit the transaction:

Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
// "c" hasn't an ID (is always zero) 

However, when i persist a child entity by explicitly calling the session.save() method, the ID is created and set immediately, even if the transaction hasn't been committed:

Child c = new Child();
session.save(c);
// "c" has an ID

Is there a way to get the ID of the child entity immediately without calling the session.save() method?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

梦中楼上月下 2024-09-03 13:04:11

这实际上取决于您使用的 ID 方案。

如果您使用自动增量字段(例如MySQL、SQL Server),则在实体保存之前不会创建ID。

如果您使用序列(例如Oracle),则当实体被持久化时将创建ID。持久

我假设您有一个自动增量字段,在这种情况下,答案是:不,如果不保留它,您就无法获得 ID。话虽如此,大多数时候您实际上并不需要该 ID。与其他实体的关系是隐式处理的。我假设您想要某种 URL 参数或表单字段的 ID?不管怎样,是的,你需要保存它。

This actually depends on the ID scheme that you use.

If you use auto increment fields (eg MySQL, SQL Server), the ID won't be created until the entity is saved.

If you use sequences (eg Oracle), the ID will be created when the entity is persisted.

I assume then that you have an auto increment field in which case the answer is: no, you can't get an ID without persisting it. That being said, you shouldn't actually need that ID most of the time. Relationships with other entities are handled implicitly. I assume then that you want the ID for some kind of URL parameter or form field? Whatever the case, yes you'll need to save it.

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