开发者

effeciently updating relationships between hibernate entities

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 invo开发者_运维问答lved, 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)?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜