Is it possible to insert a record to another table using Business Logic?

Hi,

Say I have a transaction table where all transactions go. Now I want to have a summary table which I want to update whenever an insert/update/delete is made in the transaction table. I understand that Backendless does not support aggregate function right now so this is what I thought of doing.

Let’s say Summary table has columns ownerId, total and Transaction table has columns ownerId, amount. So for each insert in Transaction, I want to update Summary.total = Summary.total + Transaction.amount. On delete, it should be Summary.total = Summary.total - Transaction.amount. For update, Summary.total = Summary.total - Transaction.amount(old) + Transaction.amount(new).

Is this possible?

Here’s my code so far.


package com.gluconitor.events.persistence_service;


import com.backendless.BackendlessCollection;
import com.backendless.geo.GeoPoint;
import com.backendless.persistence.BackendlessDataQuery;
import com.backendless.property.ObjectProperty;
import com.backendless.servercode.ExecutionResult;
import com.backendless.servercode.RunnerContext;
import com.backendless.servercode.annotation.Asset;
import com.backendless.servercode.annotation.Async;


import com.gluconitor.models.Glucose;


import java.util.HashMap;
import java.util.Map;
        
/**
* TransactionTableEventHandler handles events for all entities. This is accomplished
* with the @Asset( "Transaction" ) annotation. 
* The methods in the class correspond to the events selected in Backendless
* Console.
*/
    
@Asset( "Transaction" )
public class TransactionTableEventHandler extends com.backendless.servercode.extension.PersistenceExtender<Transaction>
{
    
  @Async
  @Override
  public void afterCreate( RunnerContext context, Transaction Transaction, ExecutionResult<Transaction> result ) throws Exception
  {
    // add your code here
    // don't know exactly what to put here
  }
    
}

Thanks,
Allen

Hi Allen,

Yes, you can do that. Just create afterCreate and afterRemove handlers for the Transaction table, and in the handlers’ code search and modify the appropriate Summary row.

Here are some doc pages which might be useful for you:
https://backendless.com/documentation/business-logic/java/bl_data_service_handler.htm
https://backendless.com/documentation/data/android/data_saving_data_objects.htm

Thanks.

I’ll look into these.