Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the "calculated" fields in a Play Framework model

What are the "best practices" to define - in Play Framework - objects that have some fields that are "calculated", rather than directly mapped to any of the fields related to an entity?

For example, I would like to define a Model for a "product" having a "list price" and "real price".

In terms of the DB, the "list price" is directly mapped to the "int listPrice" in the model class. However, the "real price" is calculated from the "list price" using additional data not related to the "product" itself (like, general store discount, department-specific discount etc. - some "business logic" involved).

Since my app needs to expose REST API (and not just a web app) - I would really want to extend the "Product" class to support the "calculated" field, so both "MyProduct.listPrice" and "MyProduct.finalPrice" will be supported.

Is it possible to add "transient" members to the model class? If not, should define a class derived from the model, and use it?

Thanks for any hint.

Max

like image 520
Max Avatar asked Jan 17 '23 17:01

Max


1 Answers

Here is the way to go

@Entity public class Product extends Model {
  ...
  public int listPrice;
  @Transient int realPrice;
  public int getRealPrice() {
    return calcRealPrice(listPrice);
  }
  ...
}
like image 189
Gelin Luo Avatar answered Feb 23 '23 06:02

Gelin Luo