DEV Community

Tommy
Tommy

Posted on

8 3

Hibernate - @Formula

Formula Annotation

The @Formula annotation is used to calculate the dynamic value of a property. @Formula takes an expression (this could be simple expression or a complex query) as a parameter. During fetch time, it evaluates the expression and assigns the evaluated value to the property.

Examples

// ex 1
@Formula("lower(datediff(curdate(), birth_date / 365)")
private int age;

// ex 2
@Formula("(select min(s.survey) from statistics s) ")
private float total;

// ex 3
private int num1;
private int num2;
private int num3;

@Formula(" num1 + num2 + num3")
private float totalSum;

Enter fullscreen mode Exit fullscreen mode

Note:
-This is only inserted in a SELECT clause!
-Be careful when using this because the SQL command you may be using may be vendor specific. In other words, this will create coupling with a particular SQL vendor.

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay