是否可以将createNativeQuery方法的结果从List转换为Map?

问题描述 投票:0回答:0

目前我有一个返回费用报告的方法。之前在使用JDBC的时候,出现了以

Map <String (category name), Long (amount of expenses for this category)>
形式返回报告的问题没有出现:

public Map<String, Long> expenseReport(long customerId, LocalDate startDate, LocalDate endDate) {
        Map<String, Long> map = new HashMap<>();
        try (Connection con = ds.getConnection()) {
            PreparedStatement ps = con.prepareStatement("SELECT c.category_name, sum(amount)\n" +
                    "FROM account as a\n" +
                    "left join transaction as t on account_from_id = account_id\n" +
                    "left join transaction_to_transaction_type tttt on t.transaction_id = tttt.transaction_id\n" +
                    "left join category c on tttt.transaction_type_id = c.category_id\n" +
                    "WHERE (t.data_created BETWEEN ? AND ?) AND a.customer_id = ? AND category_name notnull\n" +
                    "group by c.category_name;");
            ps.setObject(1, startDate);
            ps.setObject(2, endDate);
            ps.setLong(3, customerId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                map.put(rs.getString("category_name"), rs.getLong("amount"));
            }
        } catch (SQLException e) {
            throw new CustomException(e);
        }
        return map;
    }

现在,使用 JPA,我在返回地图时遇到问题:

public List expenseReport(long customerId, LocalDate startDate, LocalDate endDate) {
        return em.createNativeQuery("select c.category_name, sum(amount)\n" +
                "from account as a\n" + "left join transaction as t on account_from_id = account_id\n" +
                "left join transaction_to_category ttc on t.transaction_id = ttc.transaction_id\n" +
                "left join category c on ttc.category_id = c.category_id\n" +
                "WHERE (t.data_created BETWEEN ? AND ?) AND a.customer_id = ? AND category_name notnull\n" + "group by c.category_name;").setParameter(1, customerId).setParameter(2, startDate).setParameter(3, endDate).getResultList();
    }

如何解决这个问题?

java jpql
© www.soinside.com 2019 - 2024. All rights reserved.