I want to retrieve information about a particular user. It's a list. I tried to retrieve the information from the db and display it but it only take the last information that was inserted into the database and display it by duplicating that one information based on the size of the list. That's if the list contains 10 items. it will display 10 items with the same information. Here is the code
my service method
public List<BankAccountStatement> getAccountStatementForTheUser(String accountNumber) throws DataNotFoundException {
BankAccount bankAccount = bankAccountService.getAccountByAccountNumber(accountNumber);
List<TransactionType> transactionTypeList = transactionTypeRepository.findByBankAccount(bankAccount);
List<BankAccountStatement> bankAccountStatementList = new ArrayList<>();
BankAccountStatement bankAccountStatement = new BankAccountStatement();
for (TransactionType transactionType: transactionTypeList){
bankAccountStatement.setAmount(transactionType.getAmount());
bankAccountStatement.setCurrentBalance(transactionType.getCurrentBalance());
bankAccountStatement.setDepositorOrWithDrawalName(transactionType.getDepositorOrWithDrawalName());
bankAccountStatement.setDescription(transactionType.getDescription());
bankAccountStatement.setTransactionDate(transactionType.getTransactionDate().toString());
bankAccountStatement.setTransactionType(transactionType.getTransactionType());
bankAccountStatement.setId(transactionType.getId());
bankAccountStatementList.add(bankAccountStatement);
}
System.out.println("The list size is " bankAccountStatementList.size());
return bankAccountStatementList;
}
my repository
@Repository
public interface TransactionTypeRepository extends JpaRepository<TransactionType,Long> {
List<TransactionType> findByBankAccount(BankAccount bankAccount);
my controller
@GetMapping("/account/statement")
public ResponseEntity<List<BankAccountStatement>> getAccountStatement(@RequestParam("accountNumber") String accountNumber) throws DataNotFoundException {
return new ResponseEntity<>(transactionTypeService.getAccountStatementForTheUser(accountNumber),HttpStatus.OK);
}
CodePudding user response:
that's because you create an object once, update it, and then insert it repeatedly into the list. I'm referring to the bankAccountStatement object before the for loop. please move the bankAccountStatement creation statement inside the loop