【问题标题】:JPA @OneToMany: Returning only some values from map in a queryJPA @OneToMany:在查询中仅返回地图中的一些值
【发布时间】:2015-12-22 15:54:31
【问题描述】:

我正在尝试运行 JPA 查询以仅从我的实体返回特定字段,而不是整个实体(出于性能原因)。

在这个实体中是这样的:

@OneToMany(cascade = { CascadeType.ALL }, mappedBy = "helper", fetch = FetchType.EAGER)
@MapKeyColumn(name = "year")
public Map<Integer, DutyHistory> getDutyHistoryList() {
    return dutyHistoryList;
}

我想在我的查询中从这张地图返回多个值,例如过去 3 年的 DutyHistory 对象的字段。

我的问题是,这个查询语法是什么?我将返回的值映射到 POJO,如下所示:

@Query(value = "SELECT new com.castlemon.helpers.dto.ReportHelper(h.helperId, h.firstName, h.secondName"
            + ", h.sex, h.service, h.dateOfBirth, h.schoolGroup, h.orientationRequired, h.notes as adminNotes "
            + ", h.primaryDuty.dutyName as primaryDuty, h.secondDuty, h.secondaryDuty.dutyName as secondaryDuty "            
            + " WHERE h.travelling = 1")
    public List<ReportHelper> getTravellingHelperDetails();

【问题讨论】:

    标签: java jpa spring-data-jpa


    【解决方案1】:

    您应该使用“年份”参数创建另一个查询

    @Query(value = "SELECT new com.castlemon.helpers.dto.ReportHelper(h.helperId, h.firstName, h.secondName"
            + ", h.sex, h.service, h.dateOfBirth, h.schoolGroup, h.orientationRequired, h.notes as adminNotes "
            + ", h.primaryDuty.dutyName as primaryDuty, h.secondDuty, h.secondaryDuty.dutyName as secondaryDuty "            
            + " WHERE h.travelling = 1 AND h.year >= :yearLimit")
    public List<ReportHelper> getTravellingHelperDetailsUntilYear(String yearLimit);
    

    【讨论】:

    • 年份不是 Helper 对象上的字段,而是 DutyHistory 对象上的字段。我想知道如何在 select 语句中将其表示为离散字段。
    • 所以我猜日期的投影应该在 DutyHistory 对象上完成。它与您的 Helper 的关系取决于您的模型:加入、左加入...
    • 这将是一个左连接。
    • 所以你会有这样的东西:“select new Helper(h.id, h.toto) from Helper h left join h.dutyHistory d where d.year >= :year”跨度>
    • @uncleBounty 在这种情况下,由于 OneToMany 关系,作者可以为一个助手获取多条记录。最好使用类似“select new Helper(...) from Helper h where exists(select d from DutyHistory d where d.helper = h.helperId and d.year>=:year)”
    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    相关资源
    最近更新 更多