Looking to know how to efficiently build SQL queries that will have a varying number of OR/WHERE clauses. The goal is to reduce the number of database calls.
Currently, a method loops through a list of transaction ids that will be changing constantly, and for each id, it makes a call searching for each. The list of ids will get very large, and this will become very expensive db process.
Current Implementation
Service Class
public List<RawTransactionsDAO> getAll(){
ArrayList Integer ids = {1,2,3,4,5};
ArrayList<Transactions> ls = new ArrayList<>();
for(Integer id : ids){
List<Transactions> transactions = transactionsRepository.getById();
ls.add(transactions);
}
return ls;
}
Repository Class
@Query(value="SELECT * FROM transactions WHERE id = :id ", nativeQuery = true)
public List<Transactions> getById(Integer id);
Ideal Implementation
I would like to know how to do the following, without having to make a DB call for every id
Service Class
public List<RawTransactionsDAO> getAll(){
ArrayList Integer ids = {1,2,3,4,5};
ArrayList<Transactions> ls = transactionsRepository.getByIds(ids);
return ls;
}
Repository Class
@Query(value="SELECT * FROM transactions WHERE " +
"id = :id OR " +
"id = :id OR " +
...
// Add OR clause for every id provided
...
, nativeQuery = true)
public List<Transactions> getByIds(ArrayList<Transactions> ids);
I tried making a loop that calls the DB every time, but it is too expensive to make this many calls.