是否应该避免Hibernate双向关联?

Das*_*Das 7 java spring hibernate

在基于Spring/Hibernate的项目中,我们在两个实体之间存在一对多的关系.所需的操作是:

  • 找到孩子的父母;
  • 找到父母的孩子;
  • 当父母被移除时,我们还需要移除孩子;
  • 大规模创造孩子们.

我们提出了两种实现方法.

  1. 双向关联:子实体具有@ManyToOne将其链接到父级的列,并且父级具有@OneToMany延迟加载的子级集合.以上所有操作均可在模型中执行:

    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
    
    Run Code Online (Sandbox Code Playgroud)
  2. 单向关联:子实体具有@ManyToOne将其链接到父级的列,但父级没有任何指向子级的链接.大多数操作应该在服务方法中执行:

    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.
    
    Run Code Online (Sandbox Code Playgroud)

第一种方法似乎更容易实现(您可以重用Hibernate级联功能),但我们中的一些人认为双向关联是潜在的问题原因.

什么应该是更好的设计选择?是否存在由双向方法创建的任何众所周知的问题,性能或设计?

JB *_*zet 4

如果您的查询与 Hibernate 在延迟加载子级时在后台执行的查询执行的操作相同,那么我看不出不简单地使用 OneToMany 关联会带来什么好处。

如果您知道自己在做什么,以及实体上的每个方法调用对于数据库查询意味着什么,那么映射集合就不会有任何问题。有时遍历它们是明智的,有时最好使用临时查询以避免过多的数据库往返。关键是要了解发生了什么。

拥有关联也非常有帮助,只是为了能够在 HQL 查询中导航,而不必调用关联的 getter。