I have two Tables: Income and Expense in which I'm storing all my incomes and expense transactions and currently there is not relationship between these two tables.
@Entity
@Table(name = "expense")
public class Expense {
private BigDecimal amount;
private LocalDate dueDate;
private LocalDate datePaid;
private String description;
......
}
@Entity
@Table(name = "income")
public class Income {
private BigDecimal amount;
private LocalDate dueDate;
private LocalDate datePaid;
private String description;
......
}
At the moment I use Spring Data JPA's Specification feature to do it on an individual entity:
For Expense:
Page<Expense> expensePage = expenseRepository.findAll(expenseSpecification, paginatedList);
For Income:
Page<Income> depositPage = incomeRepository.findAll(incomeSpecification, paginatedList);
Now, I want to show all my transactions (both income and expense) on one table. So I'm now exploring performance effective solution to fetch data from both of these tables after applying filters and paginations.
I want to use specifications because the filters (amount, date etc...) are optional.
I can think of the following approaches:
- Run queries separately as mentioned above, merge the results and then apply pagination manually - this seems to be highly ineffective from performance perspective as it will be fetching whole table data
- use native SQL query with UNION but won't be able to apply filters because filters are dynamic and optional
select * from ( SELECT id, amount, paid_on as "date_paid", 'EXPENSE' as "type" FROM public.expense UNION SELECT id, amount, received_on as "date_paid", 'DEPOSIT' FROM public.deposit ) as annon_1 where annon_1.amount > 2 and annon_1.date_paid = '2021-08-10' order by annon_1.id Limit 5 offset 0
- Implement inheritance as both Income and Expense are transactions basically which has some shared attributes like date, amount, description etc... but It will be a big change as there is already lot of data in both of these tables. So I'll have to change database schema, domain classes and migrations to manage the existing data
Or if there is any other performance effective solution?