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)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

AWS GenAI Live!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️