查询仅返回其子级不为null的实体

时间:2019-12-17 13:09:00

标签: java sql hql

我有以下查询:

  @Query("SELECT new de.hiqs.project.Project(project.id, project.name, project.isArchived, " +
          "project.customer.id, project.customer.name, project.customer.smallestTimeUnitEnabled, " +
          "project.customer.smallestTimeUnit, project.defaultDailyEntrySettings.id, " +
          "project.defaultDailyEntrySettings.performanceRecord, project.defaultDailyEntrySettings.startDateHour," +
          "project.defaultDailyEntrySettings.startDateMinute, project.defaultDailyEntrySettings.endDateHour, " +
          "project.defaultDailyEntrySettings.endDateMinute, project.defaultDailyEntrySettings.pause ) " +
          "FROM Project project")
  List<Project> findAllInOneRequest();

所以我有一个查询,该查询返回具有选定属性的所有项目,以在一个请求中获得所有内容并避免N + 1问题。如您所见,ProjectDefaultDailyEntrySettings有一个关系(外键)。问题在于,并非每个项目都有一个DefaultDailyEntrySettings子级(数据库中为空)。因此,查询仅返回projects,其中有一个。我希望它返回所有projects并仅在不存在的情况下使用空值初始化defaultDailyEntrySettings而不是在没有projects的情况下不返回defaultdailyEntrySettings。有办法吗?

另一种选择是自动给每个project一个带有空字段的defaultDailyEntrySettings而不是外键为空,但是我无法弄清楚如何使用注释。

1 个答案:

答案 0 :(得分:0)

也许是这样吗?

@Query("SELECT new de.hiqs.project.Project(project.id, project.name, project.isArchived, " +
      "project.customer.id, project.customer.name, project.customer.smallestTimeUnitEnabled, " +
      "project.customer.smallestTimeUnit, project.defaultDailyEntrySettings.id, " +
      "project.defaultDailyEntrySettings.performanceRecord, project.defaultDailyEntrySettings.startDateHour," +
      "project.defaultDailyEntrySettings.startDateMinute, project.defaultDailyEntrySettings.endDateHour, " +
      "project.defaultDailyEntrySettings.endDateMinute, project.defaultDailyEntrySettings.pause ) " +
      "FROM Project project " +
      "WHERE EXISTS (SELECT 1 FROM project.defaultDailyEntrySettings)" +
      "UNION ALL " + 
      "SELECT new de.hiqs.project.Project(project.id, project.name, project.isArchived, " +
      "project.customer.id, project.customer.name, project.customer.smallestTimeUnitEnabled, " +
      "project.customer.smallestTimeUnit, null, " +
      "null, null," +
      "null, null, " +
      "null, null ) " +
      "FROM Project project " +
      "WHERE NOT EXISTS (SELECT 1 FROM project.defaultDailyEntrySettings)")
List<Project> findAllInOneRequest();