Sometimes, we need a calculated column in hibernate; at such a time, the formula feature is used. For this, we will use the @Formula
annotation with the field.
The field annotated with the @Formula
annotation is a read-only field, and the formula is only applied while using the SELECT
operation.
To show how formula works, we will change a Product
class and add a field, capitalName
, which has no physical column in the product table, as shown in the following code:
Source file: Product.java
@Entity @Table(name = "product") public class Product { @Id @GeneratedValue @Column(name = "id") private long id; @Column(name = "name") private String name; @Formula("UPPER(name)") private String capitalName; @Column(name = "price") private double price; @ManyToOne @JoinColumn(name = "category_id") private Category category; // Getters and setters }
Now, we will run a code to show how it works: