Your questions touch several topics.
1. Data modeling of invoices
The most elegant way of enforcing that an invoice contains orderlines of only one order would be to model
order <-- 1:n --> invoice <-- 1:n --> orderline
This way, the database (and class) structure would enforce that each invoice contains orderlines from exactly one order. Introducing the order id as a foreign key in the invoice, as you suggest, doesn't keep anyone to attach orderlines from different orders to that invoice.
The reason, however, that this problem is mostly solved the way you suggest (it's a quite common problem in database oriented systems supporting business processes) is that, when entering an order and its orderlines into the system, most probably nothing is known yet about invoices. So orderlines are attached directly to orders, and the invoices are built up separately later on. You might add a database constraint that allows only proper orderlines attached to an invoice.
2. Deleting, updating etc.
The next design step to take is analyzing your business process and the functionality needed to support it. This should be in no way coupled to Hibernate's functionality. When can orderlines be attached to orders? ... to invoices? Does removing an orderline from an invoice also mean removing it from the order? That can only be answered from the view of your users and their business rules.
3. Cascading
Cascading doesn't add any new database manipulation features to Hibernate. It's just a way to reduce Hibernate calls for certain routine operation sequences, like updating a parent together with all its children. Therefore, when finished with step 2, I'd only introduce those cascading rules that are totally clear to me and that support operation sequences flowing from my business requirements. It's no shame to call a few save or delete operations explicitly instead of cascading.
Also remember that your Java application is totally responsible for maintaining the correct associations between objects. So, if you want to completely delete an orderline, you'll have to cut all associations off, not only from the order, but also from the invoice. Otherwise, Hibernate will scream at you that the object you want to delete from one side will be re-created from the other side.
That said, I don't see a problem with the cascading structure you suggest.
|