skuntsel
skuntsel

Reputation: 11742

Right use case for bidirectional relationship with very many entity instances

Is it worth using @OneToMany relationship with a 'very-many' side at the collection-valued association at all?

When we have few instances, or strict logical relationship, like List<OrderLine> in Order, or Set<Phone> in Person it is all clear that we will do that. But when it comes to holding many instances, as in Set<Order> in Customer or List<Event> in Company, a simple operation like Order#setCustomer() or Event#setCompany() requires that a whole collection of elements be managed by the persistence context. Isn't it too expensive? Or should bidirectional relationships be avoided in these cases?

The consequential part is the cascade setting of these relationships. It is logical to cascade merge/persist functionality of Customer/Company to its 'children', but won't it be a waste of resources in the end?

The last but not the least is the cascade remove. It clearly fits all four relationships perfectly. But in case we are left with a unidirectional relationship of a single-valued association, we then must remove the children separately by using a query when a parent is deleted?

Right now, I am using bidirectional relationships only when the number of items is quite small and there is a clear parent-child association between the entities. Most of the job is done via a single-valued end (removing Order/Entity on its own) and via a query once the parent is removed (upon removal of Customer/Company).

After rereading some books on JPA I started to think that I'm probably not following the right way of using persistence in Java EE applications.

What is your view on using bidirectional relationships with many instances in the collection in a Java EE application in general and how do you manage cascading if you choose a unidirectional relationship in particular?

Upvotes: 0

Views: 209

Answers (1)

James
James

Reputation: 18379

If the collection is very large, then your solution is probably the best. You are better off querying for the relationship, than mapping it. But this will depend on the application.

Upvotes: 1

Related Questions