Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Hibernate bidirectional associations be avoided?

In a Spring/Hibernate based project, we have a one-to-many relationship between two entities. Required operations are:

  • find the child's parent;
  • find the parent's children;
  • when parent is being removed, we also need to remove the children;
  • mass-create the children.

We came up with two ways to implement this.

  1. 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
    
  2. 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?

like image 337
Das Avatar asked Sep 11 '11 15:09

Das


2 Answers

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.

like image 180
JB Nizet Avatar answered Sep 19 '22 15:09

JB Nizet


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.

like image 28
Moritz Both Avatar answered Sep 20 '22 15:09

Moritz Both