In a Spring/Hibernate based project, we have a one-to-many relationship between two entities. Required operations are:
We came up with two ways to implement this.
Bidirectional association: child entity has @ManyToOne
column linking it to parent, and the parent has @OneToMany
lazy-loaded collection of children. All above operations can be performed in the model:
child.getParent();
parent.getChildren(); //lazy loading
session.delete(parent); //cascade removal of the children does the trick here
session.save(parent); //cascade persist created the children
Unidirectional association: child entity has @ManyToOne
column linking it to parent, but the parent does not have any link to children. Most operations should be performed in service methods:
child.getParent(); //still in the model
Collection<Child> findChildren(Parent parent); //service method in ChildService
void deleteChildren(Parent parent); //service method in ChildService
void createChild(Parent parent, ... childAttributes); //service method in ChildService invoked for each new child.
The first approach seems to be easier to implement (you can reuse Hibernate cascading functionality) but some of us see the bidirectional associations as a potential cause of problems.
What should be a better design choice? Are there any well-known problems, performance or design, created by the bidirectional approach?
If your queries do the same thing as the queries executed behind the scene by Hibernate when it lazy-loads the children, I don't see what you gain by not simplyuse a OneToMany association.
If you know what you're doing, and what each method call on your entity means in terms of queries to the database, you shouldn't have any problem with mapped collections. Sometimes it's wise to traverse them, sometimes it's better to use an ad-hoc query to avoid too many round-trips to the database. The key is to understand what happens.
Having an asociation can also be very helpful just to be able to navigate through it in HQL queries, not necessarily to call the associated getter.
The answer by @JB Nizet says it nearly all, just one more thing: Looking at the method call samples you posted, the bidirectional method will probably make your business logic code somewhat more readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With