我有以下查询:
@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问题。如您所见,
Project
与DefaultDailyEntrySettings
有一个关系(外键)。问题在于,并非每个项目都有一个DefaultDailyEntrySettings
子级(数据库中为null)。因此查询仅返回具有1的projects
。我希望它返回所有projects
,如果不存在,只需用空值初始化defaultDailyEntrySettings
即可,而不是在没有projects
的情况下不返回defaultdailyEntrySettings
。有办法吗?另一个选择是为每个
project
自动提供一个具有空字段的defaultDailyEntrySettings
而不是外键为null,但是我无法弄清楚如何使用注释。 最佳答案
也许是这样吗?
@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();