Using formula in hibernate

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.

How to do it…

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 ...

Get Java Hibernate Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.