Annotation Interface Formula


@Target({METHOD,FIELD}) @Retention(RUNTIME) public @interface Formula
Specifies an expression written in native SQL that is used to read the value of an attribute instead of storing the value in a Column.

A Formula mapping defines a "derived" attribute, whose state is determined from other columns and functions when an entity is read from the database.

A formula may involve multiple columns and SQL operators:

 // perform calculations using SQL operators
 @Formula("sub_total * (1.0 + tax)")
 BigDecimal totalWithTax;
 

It may even call SQL functions:

 // call native SQL functions
 @Formula("upper(substring(middle_name from 0 for 1))")
 Character middleInitial;
 

By default, the fields of an entity are not updated with the results of evaluating the formula after an insert or update. The @Generated annotation may be used to specify that this should happen:

 @Generated  // evaluate the formula after an insert
 @Formula("sub_total * (1.0 + tax)")
 BigDecimal totalWithTax;
 

For an entity with secondary tables, a formula may involve columns of the primary table, or columns of any one of the secondary tables. But it may not involve columns of more than one table.

The @ColumnTransformer annotation is an alternative in certain cases, allowing the use of native SQL to read and write values to a column.

 // it might be better to use @ColumnTransformer in this case
 @Formula("decrypt(credit_card_num)")
 String getCreditCardNumber() { ... }
 
See Also:
  • Required Element Summary

    Required Elements
    Modifier and Type
    Required Element
    Description
    The formula, written in native SQL.
  • Element Details

    • value

      String value
      The formula, written in native SQL.