How to retrieve a sum of table column in play java framework

727 Views Asked by At

I am new in play and I am able to retrieve all column in database but i don't know how to get a sum of all retrieve data

model class

controller class

1

There are 1 best solutions below

4
Anton Sarov On

If you really really want to get the sum of all amount fields of your General_store model in Java you can define a method to calculate it:

private static long sumOfStores() {
    long sum = 0;
    List<General_store> allStores = General_store.all();
    for (General_store gs : allStores) {
        sum += gs.amount;
    }
    return sum;
}

Of course if you are using Java 8 you can use a stream.

But the more important part is this: DON'T DO THAT IN ANY CASE. The reason is that this is information which is stored in the database. So you should ask the database for any aggregation on this information that is rather trivial to compute. In the case of SUM this is really trivial. With the above approach you will first fetch ALL items from the database only to perform some trivial operation on one of their fields. So please use SELECT SUM(column_name) FROM table_name; and save yourself the troubles. With Ebean you can use such queries without a problem:

private static long sumOfStores() {
    final String sql = "SELECT SUM(amount) as total FROM General_store";

    SqlQuery sqlQuery = Ebean.createSqlQuery(sql);
    SqlRow row = sqlQuery.findUnique();
    return row.getLong("total");
}