简体   繁体   中英

JPQL Adding Lists into HashMap, multiplying List records

Hello fellow programmers, I want to add in loop multiple lists into HashMap. I dont't know why when its getting to second iteration records are multiplied eg there is 10 records for February( monthId = 2) and after whole loop there is 40 of them injected. Below is code:

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;
}

When comparing two numbers in sql you use = and not LIKE

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

also it looks like transactionsPerMonth is declared outside of the method and then returned, are you sure it is empty when the method is called? Probably better to declare it as a local variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM