I am going to generate simple CSV file report in Java using Hibernate and MySQL.
I am using Native SQL (because query is too complex which is not possible with HQL or Criteria query and also this doesn't matter here) part of Hibernate to fetch the data and simply writing it using any of CSVWriter api (this doesn't matter here.)
As far all is well, but the problem starts now.
Requirements:
- The report size can be with 5000K to 15000K records with 25 fields.
- It can be run on real time.
- There is one report column (let's say
finalValue
) for which I want sorting and it can be extract like this,(sum(b.quantity*c.unit_gross_price) - COALESCE(sum(pai.value),0))
.
Problem:
MySQL Indexing
can not be used forfinalValue
column (mentioned above) as it is complex combination of aggregate functions. So if execute the query (with or without limit) with sorting, it is taking 40sec, otherwise 0.075sec.
The Solutions: These are the some solutions, that I can think but each have some limitations.
Sorting using
java.util.TreeSet
: It will throw theOutOfMemoryError
, which is obvious as heap space will be exceed if I will put 15000K heavy objects.Using
limit
in MySQL query and write file for each iteration : It will take much time as every query will take same time around 50sec as without sorting limit can't be use.
So the main problem here is to overcome two parameters : Memory and Time. I need to balance both of them.
Any ideas, suggestions?
NOTE: I am not given here any snaps of code that doesn't mean question details is not enough. Code doe's not require here.