In this post I will discuss complex grouping of records for processing in a batch.There are many ways to achieve this but most of the time I see developers using temp tables. I feel that is not necessarily the most best way. So, in this post I will show how you can do the same using a map and a RecordSortedList. Avoiding multiple loops through records and also avoiding temp tables.
Scenario
Assume a scenario where you have to loop through unsorted records. Group them by the multiple fields including things like financial dimension value and balance. Then create a journal for each group.
Options
This could be achieved in a number of ways. But we want the best performing and extendable solution.
- You could do a group by selection query but that won’t work as you have to get the balance and dimensions (which are calculations).
- You could use a temp table to insert all the transaction. What if the key changes a few months later. Could be costly to develop the changes.
- You could use a map to store the RecIds and fetch the records as you loop through the map. Now you are querying the database for each fetch. You maybe also calculating the dimensions and balances during grouping and processing.
- You could use a RecordSortedList to store them. In my opinion is the cleanest and best way of doing it.
I will show how to do it with option 4 – using a RecordSortedList. Below in the screenshot you have 3 classes.
- NAVAX_Process – Main batch class that is executed.
- NAVAX_ProcessHandler – Does the grouping of the records and storing them in their respective class instance which is group in a map.
- NAVAX_ProcessTask – The processing task class. Has an execute method which you would put
The handler class creates a map to store a container as the key and the class instance as the value. The key is a container because we are going to group my multiple values. At the end we will loop through the map to call the execute method for each class instance that is stored.
The handler class has an addRecord method. This will do the grouping by storing the values in a key. This is where you would store the calculated values to group by (I am not doing it here but using the customer group and the delivery mode instead).
The execute method in the handler class loops through the map and calls the execute method of the class instance that was stored.
Result
In this example I am going to show the result in an infolog.