简体   繁体   中英

Spring Hibernate uni-directional One-To-Many associations with good performance

According to these 2 articles:

vlahidmihalcea.com

thorben-janssen.com

Uni-directional associations should be avoided. Best practice (let's stick to few entities on the many-side) would be to add bi-directional associations.

This looks strange to me in 2 aspects:

  1. In the DB you create a third table to map the @onetomany. From what I know, it is rather bad (for simplicity and performance), since you can just use one foreign-key if you query effectively. Also if you do own queries, you have to consider the third table, leading to more work and possible inconsistencies.

  2. In the java-code you have a List in the parent and have a reference to the parent element for each child. While it doesn't seem like a huge performance-issue in the java application, it still requires work to avoid inconsistencies. There are ways to deal with this, but it is still vulnerable to inconsistencies if you are not aware.

So what would be the best way in my opinion?

  1. In the java-application you would only have the List in the parent class.
  2. In the DB you don't have a third table but only a foreign key.

Is there a way to implement this, while still having good performance? The articles I am referencing are both only Hibernate, does Spring have a solution to this problem?

You don't need a join table for this. You can just map it like this:

@Entity
public class Parent {
  @OneToMany(mappedBy = "parent")
  Set<Child> children;

  public Set<Child> getChildren() {
    return Collections.unmodifiableSet(children);
  }

  public void addChild(Child c) {
    children.add(c);
    c.setParent(this);
  }
}

@Entity
public class Child {
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "fk_column_name")
  private Parent parent;

  void setParent(Parent p) {
    this.parent = p;
  }
}

This will work exactly the way you like. Keeping the associations in sync is not a big deal IMO. You just need to keep the parent association private and manage the setting of the field through package-private methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM