简体   繁体   English

Spring Hibernate 单向一对多关联,性能良好

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

According to these 2 articles:根据这两篇文章:

vlahidmihalcea.com vlahidmihalcea.com

thorben-janssen.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.在数据库中,您创建第三个表来映射@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.在 java 代码中,父元素中有一个 List,并且每个子元素都有一个对父元素的引用。 While it doesn't seem like a huge performance-issue in the java application, it still requires work to avoid inconsistencies.虽然它在 Java 应用程序中似乎不是一个巨大的性能问题,但它仍然需要努力避免不一致。 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.在 java 应用程序中,您只会在父类中拥有 List。
  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?我引用的文章都只是Hibernate,Spring有解决这个问题的方法吗?

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.保持关联同步并不是 IMO 的大事。 You just need to keep the parent association private and manage the setting of the field through package-private methods.您只需要保持父关联私有并通过包私有方法管理字段的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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