有效更新休眠实体之间的关系

发布于 2024-11-18 20:16:16 字数 502 浏览 3 评论 0原文

我在两个休眠实体之间有一个 m2m 关系,我们称它们为电影和演员,我已经用双向链接设置了它们。显然,这被建模为电影表、演员表以及数据库中两者之间的外键连接表。

用户界面允许您更新演员和电影之间的关系。在内部,UI 使用所涉及的电影和演员的 id 跟踪屏幕上的更新,然后在您点击“保存”时将电影 id 和演员 id 列表发送到控制器。

现在我的问题:假设我通过在数据库中添加四个演员来更新电影。我有要添加的 Actor id 列表,但我没有实际的 Actor 对象,因为我只从 UI 收到了它们的 id。

要进行此更新,我是否需要填充四个成熟的 Actor 对象,只是将它们添加到我的 Movie 对象中,以便我可以将其存储回数据库?换句话说,我是否需要首先从数据库中进行选择才能进行更新?进行额外的 select 调用似乎效率很低,因为真正更新的只是向连接表添加一些行,而且我已经拥有执行此操作所需的所有信息。

因此,hibernate 是否提供了一种方便的方法来直接将键添加到连接表本身(无需编写自定义原始 sql 查询)?

I have an m2m relationship between two hibernate entities, let's call them Movies and Actors, which I've setup with bidirectional links. Obviously this is modeled as a movies table, and actors table, and a join table of foreign keys between the two in the db.

The UI lets you update relationships between Actors and Movies. Internally, the UI tracks your onscreen updates using the ids of the movies and actors involved, then sends the movie id with a list of actor ids to the controller when you hit "save".

Now my question: suppose I update a Movie by adding four Actors to it in the db. I have the list of actor ids to add, but I don't have the actual Actor objects, because I've only received their ids from the UI.

To make this update, do I need to populate four full-blown Actor objects just to add them to my Movie object so that I can store it back to the db? In other words, do I need to first select from my db just to then do the update? It seems inefficient to make that extra select call since all that will really be updated is adding some rows to the join table, and I already have all the information required to do that.

Does hibernate therefore provide a handy way to directly add keys to the join table itself (without writing a custom raw sql query)?

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

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

发布评论

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

评论(1

ゝ偶尔ゞ 2024-11-25 20:16:16

Session.load 做你想要的。它返回一个仅包含演员 ID 的 Actor 代理,并假设您知道该演员存在于数据库中。如果没有,您的事务当然会在更新后回滚,因为外键约束已损坏。
如果参与者已经存在于会话中,则将其返回。如果事务最终需要调用其中一个参与者的方法,则无需探测:它是一个代理,并且将在需要时加载参与者的状态。

JPA EntityManager 的等效方法是 getReference

Session.load does what you want. It returns a proxy of Actor containing only the ID of the actor, and assumes you know that the actor exists in the database. If it doesn't, your transaction will of course rollback after the update because of a broken foreign key constraint.
If the actor is already present in the session, it's returned. If the transaction finally needs to call a method on one of the actors, no probem: it's a proxy, and the state of the actor will be loaded if needed.

The equivalent method with a JPA EntityManager is getReference.

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