【问题标题】:JPQL Adding Lists into HashMap, multiplying List recordsJPQL 将 List 添加到 HashMap 中,将 List 记录相乘
【发布时间】:2019-07-22 19:58:23
【问题描述】:

各位程序员,你好,我想在循环中添加多个列表到 HashMap 中。我不知道为什么当它到达第二次迭代记录时会成倍增加,例如二月有 10 条记录(monthId = 2),在整个循环之后有 40 条记录被注入。下面是代码:

public HashMap<String,List<Transaction>> convertTransactionsPerMonth(int 
userId){
    for(int monthId = 1; monthId < 13; monthId++){
    ArrayList<Transaction> transactionsFromDatabase = new ArrayList<> 
    (entityManager
            .createQuery("SELECT t FROM Transaction t WHERE 
    MONTH(t.transactionDate) LIKE :monthId AND t.user.id = :userId", 
    Transaction.class)
            .setParameter("monthId", monthId)
            .setParameter("userId", userId)
            .getResultList());
    transactionsPerMonth.put(Months.getById(monthId), 
    transactionsFromDatabase);
    }
    return transactionsPerMonth;
}

【问题讨论】:

    标签: java spring hibernate jpql


    【解决方案1】:

    在 sql 中比较两个数字时,您使用 = 而不是 LIKE

    "SELECT t FROM Transaction t WHERE 
    MONTH(t.transactionDate) = :monthId AND t.user.id = :userId"
    

    看起来transactionsPerMonth在方法之外声明然后返回,你确定调用方法时它是空的吗?将其声明为局部变量可能更好。

    【讨论】:

    • 感谢比较两个数字的建议,这很有用。 transactionsPerMonth 一开始是空的,我这样做的原因是因为我想在另一个只接收它的字符串键的方法中使用它。这是这个 HashMap 的声明: private HashMap> transactionsPerMonth = new HashMap();
    猜你喜欢
    • 2021-01-21
    • 2017-09-15
    • 1970-01-01
    • 2018-07-17
    • 2014-01-15
    • 1970-01-01
    • 2020-07-27
    • 2012-12-26
    • 2022-12-17
    相关资源
    最近更新 更多