Hibernate annotations tutorial

User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active
 

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, 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.

1. Start by downloading Hibernate distribution from the source.

2. Unzip the distribution and create a new Java Project

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();
    }

}

Notice: If you boot Hibernate yourself, you need to use the AnnotationConfiguration class instead of the Configuration class.

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. If you are running Hibernate as standalone you will need the Hibernate core libraries, some JBoss client logging libraries and of course your JDBC libraries.
Add Hibernate and JBoss libraries

Here's a snapshot of the Eclipse libraries needed:

hiberante-annotations
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("-------------------");
        }

    }

}