原创

選択クエリの結果をまとめて HashMap にプロジェクトする

温馨提示:
本文最后更新于 2024年04月12日,已超过 48 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我
// input: list of local date array where first element is start date and second element is end date
// output: LicenseConsumption model object
public LicenseConsumption getLicenseConsumption(Map<String, LocalDate[]> dateRanges, String productId) {
    Parameters params = Parameters.with("productId", productId);
    StringBuilder queryBuilder = new StringBuilder();
    queryBuilder.append("SELECT ");
    
    // Dynamically construct the select clause
    int index = 0;
    for (Map.Entry<String, LocalDate[]> entry : dateRanges.entrySet()) {
        LocalDate startDate = entry.getValue()[0];
        LocalDate endDate = entry.getValue()[1];
        params.and("startDate" + index, startDate);
        params.and("endDate" + index, endDate);
        queryBuilder.append("COUNT(DISTINCT CASE WHEN latest_eu_date >= :startDate").append(index)
                    .append(" AND latest_eu_date < :endDate").append(index).append(" THEN el.employee.id END) AS ")
                    .append(entry.getKey());
        if (index < dateRanges.size() - 1) {
            queryBuilder.append(", ");
        }
        index++;
    }
    
    queryBuilder.append(" FROM LicenseEntity l ");
    queryBuilder.append("LEFT JOIN EmployeeLicenseEntity el ON el.product.id = l.product.id ");
    queryBuilder.append("LEFT JOIN ( ");
    queryBuilder.append("   SELECT eu.employee.id AS employeeId, eu.product.id AS productId, MAX(eu.date) AS latest_eu_date ");
    queryBuilder.append("   FROM EmployeeUsageEntity eu ");
    queryBuilder.append("   GROUP BY eu.employee.id, eu.product.id ");
    queryBuilder.append(") AS latest_eu ON latest_eu.productId = el.product.id AND latest_eu.employeeId = el.employee.id ");
    queryBuilder.append("WHERE l.product.id = :productId ");
    queryBuilder.append("GROUP BY l.product.id");

    // Execute the query and get the result as Object array
    PanacheQuery<LicenseConsumption> result = find(queryBuilder.toString(), params).firstResult();

    // Construct the LicenseConsumption object
    LicenseConsumption licenseConsumption = new LicenseConsumption();
    // Populate consumptionRanges map from the result
    Map<String, Integer> consumptionRanges = new HashMap<>();

    
    licenseConsumption.setConsumptionRanges(consumptionRanges);
    return licenseConsumption;
}

ここの決めは正しいです。すでにチェックしてました。結果セットには複数の列を含めることができます。動的配置によって異なりますが、100 または 1 の場合があります。結果を HashMap<String 、整数> に投影したらどうすればよいですか? string は列の名前、Integer はレコード結果が 1 しかない場合の値です。

事前定義されたプロパティを使用して独自のクラスを作成して、書き込みが機能するかどうかを確認しようとしましたが、実際に機能しました。としています

正文到此结束
热门推荐
本文目录