如何优化hibernate多态查询不加入所有子类

时间:2015-08-20 14:36:02

标签: java hibernate optimization polymorphic-associations

我试图优化hibernate查询并遇到hibernate使查询比我预期的更复杂的问题。

我有一个基类 WorkUnit 和几个子类 CheckEmployee,Meeting,HomeCareRequest WorkUnitAssignment ,它们指向 WorkUnit

以下是课程的草图:

@Entity
@Table(name = "WORK_UNIT_ASSIGNMENT")
public class WorkUnitAssignmentEntity {
    private WorkUnitEntity workUnit;
    ...

    @ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
    @JoinColumn(name = "WORK_UNIT_A_WORK_UNIT_ID")
    public WorkUnitEntity getWorkUnit() {
        return workUnit;
    }
}

@Entity
@Table(name = "WORK_UNIT")
@Inheritance(strategy = InheritanceType.JOINED)
public class WorkUnitEntity  {
}

@Entity
@Table(name = "CHECK_EMPLOYEE")
@PrimaryKeyJoinColumn(name="CHECK_EMPLOYEE_ID")
public class CheckEmployee extends WorkUnitEntity {
}

@Entity
@Table(name = "MEETING")
@PrimaryKeyJoinColumn(name = "MEETING_ID")
public class MeetingEntity extends WorkUnitEntity {
}

@Entity
@Table(name = "HCIS_HC_REQUEST")
@PrimaryKeyJoinColumn(name = "HC_REQUEST_ID")
public class HomeCareRequestEntity extends WorkUnitEntity {
}

我想仅使用 HomeCareRequest 加载 WorkUnitAssignment 。 这是我的问题:

DetachedCriteria criteria = DetachedCriteria.forClass(WorkUnitAssignmentEntity.class);
DetachedCriteria dc = criteria.createCriteria("workunit", "workunit");
dc.add(Restrictions.eq("workunit.class", HomeCareRequestEntity.class));

Hibernate生成这样的sql:

select ... from WORK_UNIT_ASSIGNMENT this_, WORK_UNIT joinworkun1_, 
           HC_REQUEST joinworkun1_1_, CHECK_EMPLOYEE joinworkun1_2_, 
           MEETING joinworkun1_3_
where this_.WORK_UNIT_A_WORK_UNIT_ID=joinworkun1_.WORK_UNIT_ID and 
joinworkun1_.WORK_UNIT_ID=joinworkun1_1_.HC_REQUEST_ID(+) and 
joinworkun1_.WORK_UNIT_ID=joinworkun1_2_.CHECK_EMPLOYEE_ID(+) and 
joinworkun1_.WORK_UNIT_ID=joinworkun1_3_.MEETING_ID(+) and 
case
when joinworkun1_1_.HC_REQUEST_ID is not null then 1
when joinworkun1_2_.CHECK_EMPLOYEE_ID is not null then 2
when joinworkun1_3_.MEETING_ID is not null then 3
when joinworkun1_.WORK_UNIT_ID is not null then 0
end=?

此查询需要额外加入 CHECK_EMPLOYEE 会议。 我的问题是如何配置hibernate不进行这些连接。

我尝试将继承更改为singe表并在子类中使用辅助表但结果是相同的。

0 个答案:

没有答案