【问题标题】:Using relationships like @OneToMany, @ManyToOne in hibernate is good practice or not? [closed]在hibernate中使用@OneToMany、@ManyToOne之类的关系是好习惯吗? [关闭]
【发布时间】:2017-03-01 13:58:04
【问题描述】:

在 java spring Boot hibernate 项目中使用@OneToMany、@ManyToOne 之类的关系是好习惯吗?

【问题讨论】:

    标签: java hibernate jpa


    【解决方案1】:

    不管良好的实践,这里的重点是您有两种选择来对此进行建模:

    1. 选择在Employee 上手动分配Department 的ID。
    2. 在保存时将新的Employee 与现有的Department 实体相关联。

    你选择哪一个取决于许多因素。

    在使用未施加外键约束的旧系统或您不想施加这些约束的情况下,通常会选择前者。这通常是两者中较为罕见的情况,但在特定情况下是有意义的。

    后者是更受欢迎的方法,因为实体域模型不仅最好地代表了数据库模型所隐含的限制和约束,而且还传达了您的域专家使用的限制。例如,如果Employee 未关联到有效的Department,则无法保存。因此,您将 Department 分配给员工而不是其标识符。

    您所做的选择自然会对您可以针对实体模型发出的查询类型产生一些影响,但影响很小。

    private Department getDepartmentById(Long departmentId)
      throws InvalidDepartmentException {
      try {
        return entityManager.getReference( Department.class, departmentId );
      }
      catch ( EntityNotFoundException e ) {
        throw new InvalidDepartmentException( departmentId, e );
      }
    } 
    
    private List<Employee> getEmployeesNoAssociation(Long departmentId) 
      throws InvalidDepartmentException {
      final Department dept = getDepartmentById( departmentId );
      return entityManager
        .createQuery( "SELECT e FROM Employee e WHERE e.departmentId = :id", Employee.class )
        .setParameter( "id", dept.getId() )
        .getResultList();
    }
    
    private List<Employee> getEmployeesWithAssociation(Long departmentId) 
      throws InvalidDepartmentException {
      final Department dept = getDepartmentById( departmentId );
      return entityManager
        .createQuery( "SELECT e FROM Employee e WHERE e.department = :dept", Employee.class )
        .setParameter( "dept", dept )
        .getResultList();
    }
    

    简而言之,良好做法是将您的域建模为预期使用的域。这如何适用于您是否使用关联映射很大程度上取决于您的情况。

    【讨论】:

      猜你喜欢
      • 2015-08-03
      • 2013-03-30
      • 2020-08-25
      • 2021-03-15
      • 2023-01-06
      • 2015-02-18
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多