Using Hibernate annotations in your applications

In the former Hibernate tutorial we have shown how to create a simple standalone application XML configuration files to map Entities. In this short tutorial we will learn how to replace the Hibernate’s XML class mapping files with simple JPA annotations.

Hibernate Annotations Overview

Hibernate, like all other object/relational mapping tools, requires metadata that governs the transformation of data from one representation to the other. Hibernate Annotations provides annotation-based mapping metadata.

Hibernate EntityManager implements the programming interfaces defined by the JPA persistence specification and together with Hibernate Annotations offers a complete JPA persistence solution on top of the Hibernate Core.

So,  in order to map your database structure you can use Hibernate core (without annotations) or Hibernate with JPA annotations. Depending on the type of your business and technical needs, you can use either, however, using Hibernate with JPA annotations you can at any time switch to JPA compliant solution by simply replacing hibernate.cfg.xml with persistence.xml.

Basic annotations

Here is a list of basic Annotations you can place in an Hibernate/JPA Application:

@Entity

Annotate all your entity beans with @Entity.

@Entity
public class Company implements Serializable {
...
}

@Table

Specify the database table this Entity maps to using the name attribute of @Table annotation. In the example below, the data will be stored in ‘company’ table in the database.

@Entity
@Table(name = "company")
public class Company implements Serializable {
...
}

@Column

Specify the column mapping using @Column annotation.

@Entity
@Table(name = "company")
public class Company implements Serializable {

  @Column(name = "name")
  private String name;
  
...
}

@Id

Annotate the id column using @Id.

@Entity
@Table(name = "company")
public class Company implements Serializable {

  @Id
  @Column(name = "id")
  private int id;
  
...
}

@GeneratedValue

Let database generate (auto-increment) the id column.

@Entity
@Table(name = "company")
public class Company implements Serializable {

  @Id
  @Column(name = "id")
  @GeneratedValue
  private int id;
  
...
}

@Version

Control versioning or concurrency using @Version annotation.

@Entity
@Table(name = "company")
public class Company implements Serializable {

  @Version
  @Column(name = "version")
  private Date version;
  
...
}

@OrderBy

Sort your data using @OrderBy annotation. In example below, it will sort all contacts in a company by their firstname in ascending order.

  @OrderBy("firstName asc")
  private Set contacts;

@Transient

Annotate your transient properties with @Transient.

@Transient
public boolean isGoodCustomer() {
return checkMoney(money);
}

@Lob

Annotate large objects with @Lob. (Read more: How to map a BLOB field with JPA? )

@Lob
@Column(name = "picture", columnDefinition="BLOB")
private byte[] picture;

A sample Hibernate application using Annotations

In the first example, we will test Hibernate annotations using a standalone application. For this purpose we will create a Java Project using Eclipse. Then we will map the class “Application” which maps the table “APPS”, stored in an Oracle database.

Here’s the class hibernate.objects.Application.java

package hibernate.objects;
import javax.persistence.*;

@Entity
@Table(name="Applicazione")

public class Application  implements java.io.Serializable {

     private Long idApplicazione; 
     private String dsc;
     private String eseguibile;
   

    public Application() {  }
       
    @Id
    @Column(name="id_applicazione")
    public Long getIdApplicazione() {
        return this.idApplicazione;
    }
    
    public void setIdApplicazione(Long idApplicazione) {
        this.idApplicazione = idApplicazione;
    }

    public String getDsc() {
        return this.dsc;
    }
    
    public void setDsc(String dsc) {
        this.dsc = dsc;
    }

    public String getEseguibile() {
        return this.eseguibile;
    }
    
    public void setEseguibile(String eseguibile) {
        this.eseguibile = eseguibile;
    }
     
    
}

As you can see @Entity declares the class as an entity (i.e. a persistent POJO class), @Id declares the identifier property of this entity. Since the table name does not correspond to the class name, we are using the @Table annotation to reference the table name.

The same happens for the column idApplicazione which maps the id_applicazione with the @Column annotations. All other columns bear the same database column name.

In order to start an Hibernate Session we will create an utility class named util.HibernateUtil.java

package util;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {


    private static final SessionFactory sessionFactory;

    static {

        try {
            sessionFactory = new AnnotationConfiguration()
            .configure().buildSessionFactory();

        } catch (Throwable ex) {
            // Log exception!
            throw new ExceptionInInitializerError(ex);
        }

    }

    public static Session getSession()

    throws HibernateException {
        return sessionFactory.openSession();
    }

}

Now, all you have to do, is creating the file hibernate.cfg.xml (we’ll place it in the src folder for convenience). This file contains the JDBC configuration and merely the list of Entities mapped:

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.password">tiger</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@192.168.1.1:ORACLEDB</property>
        <property name="hibernate.connection.username">scott</property>
        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>


        <mapping class="hibernate.objects.Application" />
    </session-factory>

</hibernate-configuration>

That’s all. Finish by adding the required libraries to your project.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.6.3.Final</version>
</dependency>

The following class will test your Hibernate engine with a simple Query:

package sample;

import hibernate.objects.Application;

import java.util.List;
import util.HibernateUtil;
import org.hibernate.*;

public class ExampleAnnotation {
   
    public static void main(String[] args) throws Exception {
        Session session = HibernateUtil.getSession();
        
        Query q = session.createQuery("from hibernate.objects.Application");
        List list = q.list();
        for(Application app:list) {
            
              System.out.println(app.getIdApplicazione());
              System.out.println(app.getDsc());               
              System.out.println("-------------------");
        }

    }

}
Found the article helpful? if so please follow us on Socials