@Formula Annotation in Hibernate Example - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In hibernate, we have many annotations. Each annotation has its importance to perform an operation. Likewise, @Formula is a hibernate annotation to calculate the dynamic value and assign that value to the property.
@Formula annotation takes the expression as a parameter, and at fetch time it will evaluate the expression and assigns an evaluated 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 can be applied on top of the property.
In this tutorial, we are going to calculate the Employee total salary, using the @Formula annotation in hibernate. 
To make the example as simple, we figure the total employee salary like below.
Employee total salary = basic + conveyance + hra;
Let’s implement this calculation by using @Formula annotation in hibernate. Project Structure: 
Required Dependencies :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springframework.samples</groupId>
  <artifactId>Hibernate-Formula-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <properties>

    <!-- Generic properties -->
    <java.version>1.6</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <!-- Spring -->
    <spring-framework.version>3.2.3.RELEASE</spring-framework.version>

    <!-- Hibernate / JPA -->
    <hibernate.version>4.2.1.Final</hibernate.version>

    <!-- Logging -->
    <logback.version>1.0.13</logback.version>
    <slf4j.version>1.7.5</slf4j.version>

    <!-- Test -->
    <junit.version>4.11</junit.version>

  </properties>
  
  <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>	
</project>
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;
    }

}

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.
Happy Learning 🙂


Hibernate-Formula-Annotation-Example

File size: 15 KB
Downloads: 930


Calling Stored Procedures in Hibernate
Hibernate Filters Example Annotation
AngularJs Search Filter Example
Basic Hibernate Example with XML Configuration
Hibernate Composite Key Mapping Example
Hibernate One to One Mapping using primary key (XML)
Hibernate 4 Example with Annotations Mysql
Hibernate Criteria API with Example
Hibernate Left Join Example
Hibernate One To Many Using Annotations
Hibernate Table per Class strategy Annotations Example
@Qualifier annotation example in Spring
What is Hibernate
Hibernate cache first level example
hibernate update query example

Calling Stored Procedures in Hibernate
Hibernate Filters Example Annotation
AngularJs Search Filter Example
Basic Hibernate Example with XML Configuration
Hibernate Composite Key Mapping Example
Hibernate One to One Mapping using primary key (XML)
Hibernate 4 Example with Annotations Mysql
Hibernate Criteria API with Example
Hibernate Left Join Example
Hibernate One To Many Using Annotations
Hibernate Table per Class strategy Annotations Example
@Qualifier annotation example in Spring
What is Hibernate
Hibernate cache first level example
hibernate update query example






Sumit
July 17, 2020 at 1:45 pm - Reply 

I am seeing the below error. My POJO looks like this:
private Long longOldValue;
private String oldValue;
private Long longNewValue;
private String newValue;
private long created;
private String reasonChange;
@Formula(“longNewValue-longOldValue”)
private Long difference;
java.sql.SQLSyntaxErrorException: Unknown column ‘applicatio1_.longNewValue’ in ‘field list’
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.19.jar:8.0.19]










Sumit
July 17, 2020 at 1:45 pm - Reply 

I am seeing the below error. My POJO looks like this:
private Long longOldValue;
private String oldValue;
private Long longNewValue;
private String newValue;
private long created;
private String reasonChange;
@Formula(“longNewValue-longOldValue”)
private Long difference;
java.sql.SQLSyntaxErrorException: Unknown column ‘applicatio1_.longNewValue’ in ‘field list’
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.19.jar:8.0.19]




I am seeing the below error. My POJO looks like this:
private Long longOldValue;
private String oldValue;
private Long longNewValue;
private String newValue;
private long created;
private String reasonChange;
@Formula(“longNewValue-longOldValue”)
private Long difference;
java.sql.SQLSyntaxErrorException: Unknown column ‘applicatio1_.longNewValue’ in ‘field list’
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.19.jar:8.0.19]
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache