Wednesday , June 28 2017
Home / Hibernate / @Formula Annotation in Hibernate Example

@Formula Annotation in Hibernate Example

In hibernate, we have number of annotations. Each annotation has its own importance to perform an operation. Like wise @Formula is a hibernate annotation, which is used on top of the property, to calculate the dynamic value and assign that value to the property.

@Formula annotation takes the parameter (expression) and at fetch time, it will evaluate the expression and assign the value to the property. This @Formula parameter can be as complex as we want. That means, it may be a simple expression or it may be a complex query.

This is also an important hibernate interview question, if you have more than 3 years experience.

In this tutorial, we are going to calculate the Employee total salary, using the @Formula annotation in hibernate.

@Formula Hibernate Example :

To make the example as simple, we just calculate the employee total salary like below.

Employee total salary = basic + conveyance + hra;

Let’s implement this calculation by using @Formula annotation in hibernate.

Project Structure :

@formula Example

Required Dependencies :

pom.xml


    <dependencies>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!-- MySQL Driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.0.5</version>
        </dependency>
    </dependencies>    

Hibernate POJO :

Salaries.java


package com.onlinetutorialspoint.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Formula;

@Entity
@Table(name = "salaries")
public class Salaries {
    @Id
    @Column(name = "empid")
    private int empId;
    @Column(name = "empname")
    private String empName;
    @Column(name = "basic")
    private int basic;
    @Column(name = "conveyance")
    private int conveyance;
    @Column(name = "hra")
    private int hra;

    @Formula(" basic + conveyance + hra ")
    private float total;

    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public int getBasic() {
        return basic;
    }

    public void setBasic(int basic) {
        this.basic = basic;
    }

    public int getConveyance() {
        return conveyance;
    }

    public void setConveyance(int conveyance) {
        this.conveyance = conveyance;
    }

    public int getHra() {
        return hra;
    }

    public void setHra(int hra) {
        this.hra = hra;
    }

    public float getTotal() {
        return total;
    }

    public void setTotal(float total) {
        this.total = total;
    }

}

Lets Run the Example :

Main.java


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import com.onlinetutorialspoint.bean.Salaries;

public class Main {
    private static final SessionFactory concreteSessionFactory;
    static {
        try {
            concreteSessionFactory = new AnnotationConfiguration()
                    .configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static Session getSession()
            throws HibernateException {
        return concreteSessionFactory.openSession();
    }

    public static void main(String[] args) {
        Session session=getSession();
        Transaction tx = session.beginTransaction();
        Salaries salaries = new Salaries();
        salaries.setEmpName("Rahul");
        salaries.setBasic(10000);
        salaries.setConveyance(3000);
        salaries.setHra(7000);
        session.save(salaries);
        tx.commit();
        
        Salaries d=  (Salaries)session.get(Salaries.class,new Integer(1));    
        
        System.out.println("Employee Total Salary :"+d.getTotal());

    }

}

On the above example, we use session.get(Salaries.class,new Integer(1)) to get
the Salaries details from hibernate cache or database.

Hibernate: insert into salaries (basic, conveyance, empname, hra, empid) values (?, ?, ?, ?, ?)
Hibernate: select salaries0_.empid as empid1_0_0_, salaries0_.basic as basic2_0_0_, salaries0_.conveyance as conveyan3_0_0_, salaries0_.empname as empname4_0_0_, salaries0_.hra as hra5_0_0_,  salaries0_.basic + salaries0_.conveyance + salaries0_.hra  as formula0_0_ from salaries salaries0_ where salaries0_.empid=?
Employee Total Salary :20000.0

On the above example, we use @Formula annotation for simple expression. If we want to make this some more extent, we do.. Like below.

@Formula(“(select min(s.hra) from salaries s) “)
private float total;

If you change the code like above, you can get the minimum hra in salaries table.

Download Example

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Hibernate Native SQL Query Example

In this tutorials, we are going to learn about Hibernate Native SQL with example. Hibernate …

Leave a Reply

Your email address will not be published. Required fields are marked *