How To use @Formula in Hibernate

Overview

From the official documentation, a Formula mapping defines a “derived” attribute (that means, not persisted), whose state is determined from other columns and functions when an entity is read from the database.

You’d probably know other annotation that make a field not persisted to the database: @Transient. While they both allow you to create fields that are not persisted to the database, there are some notable differences. However, that’s the topic of another post. I only focus on @Formula in this post.

Understanding @Formula

The @Formula annotation let you create virtual, non-persistent properties that are derived from expressions or SQL formulas.

That means you can do math and execute query using this annotation.

Let’s consider some examples:

    @Formula("age * 10")
    private int tenAge;

    @Formula("(select count(*) from player)")
    private int playerCount;

These values are calculate at run time, when the entity is read from the database.

Limitations and Considerations

While @Formula is a powerful feature, there are some limitations you need to be aware of:

Database Independence: Be careful when using database-specific functions in the formula, as it might lead to issues when switching databases.

Read-Only: Properties annotated with @Formula are read-only and cannot be updated directly.

Performance: Complex formulas might impact query performance. That means you always need to test the performance of queries involving computed properties, especially if they involve large datasets.

Conclusion

In this post, I’ve showed you how the @Formula annotation. It’s a quite powerful tool to calculate the data based on existing fields or to extract data from queries (SELECT). Make sure you do the performance check when using @Formula since it may cause issues, especially on large dataset.

Leave a Comment