Das*_*Das 7 java spring hibernate
在基于Spring/Hibernate的项目中,我们在两个实体之间存在一对多的关系.所需的操作是:
我们提出了两种实现方法.
双向关联:子实体具有@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)单向关联:子实体具有@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级联功能),但我们中的一些人认为双向关联是潜在的问题原因.
什么应该是更好的设计选择?是否存在由双向方法创建的任何众所周知的问题,性能或设计?
如果您的查询与 Hibernate 在延迟加载子级时在后台执行的查询执行的操作相同,那么我看不出不简单地使用 OneToMany 关联会带来什么好处。
如果您知道自己在做什么,以及实体上的每个方法调用对于数据库查询意味着什么,那么映射集合就不会有任何问题。有时遍历它们是明智的,有时最好使用临时查询以避免过多的数据库往返。关键是要了解发生了什么。
拥有关联也非常有帮助,只是为了能够在 HQL 查询中导航,而不必调用关联的 getter。
归档时间: |
|
查看次数: |
2113 次 |
最近记录: |