获取cascade=“all”中子级的ID关系,同时将其添加到集合中,在 Hibernate 中
我有两个实体“父”和“子”,它们通过双向一对多关系链接,级联属性设置为“全部”。 使用下面的代码将子对象添加到父子集合时,在提交事务之前我无法获取持久化子实体的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这实际上取决于您使用的 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.