Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp
Hibernate version:3.1
I'm confused about the correct way to map a parent-child relationship efficiently. The common problems faq,
http://hibernate.org/116.html#A10, indicates that you must update both sides of a bi-directional association, as follows:
Code:
parent.getChildren().add(child);
child.setParent(parent);
However, to be efficient, the tips and tricks FAQ,
http://hibernate.org/118.html#A20, suggests that you can create an association to an object without actually loading the object from the database (assuming lazy enabled):
Code:
Item itemProxy = (Item) session.load(Item.class, itemId);
Bid bid = new Bid(user, amount, itemProxy);
session.save(bid);
Assuming for a moment that Item is parent and Bids is child, and Items had a collection of Bids, it would be necessary to add bid to that collection (e.g.: itemProxy.getBids().add(bid)). The act of calling a method on itemProxy will load it (or so it seems by experiment). So, how you do you work around this?
The performance FAQ,
http://hibernate.org/117.html#A9 suggests that you can refactor to use many-to-one associations to avoid this problem. However, that means that the Parent has no association to the Child, and so you cannot define a cascade saves, updates and deletes from parent to child, which is often desirable (e.g. sometimes, you'll have the Parent and want to cascade an update, sometimes you'll create a new association, and don't want to reload the parent, if you can help it.
So is it possible to have a parent-child relationship with cascade (parent to child), without requiring that the Parent be loaded just to add a child (assuming you know the ID of the parent)? If this were simple SQL, I'd just do an insert, and as long as the parent exists, it works. Of course, in SQL, I've also got to map all the attributes and explicitly insert (or update) myself.
thanks!