Hibernate Annotations

Hibernate Annotations: Hibernate needs a metadata to govern the transformation of data from POJO to database tables and vice versa.

Hibernate Annotations

Hibernate Annotations

     

You have already familiar with hibernate so, here you will learn only the Hibernate Annotations part. 

Download Source Code

Hibernate Annotations: Hibernate needs a metadata to govern the transformation of data from POJO to database tables and vice versa. Most commonly XML file is used to write the metadata information in Hibernate. The Java 5 version has introduced a powerful way to provide the metadata to the JVM. The mechanism is known as Annotations. Annotation is the java class which is read through reflection mechanism during the runtime by JVM and does the processing accordingly. The Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code this helps the user to understand the table structure and POJO simultaneously during the development. This also reduces the management of different files for the metadata and java code.

Prerequisite for setting the project :-

  1. Make sure you have Java 5.0 or higher version .
  2. You should have Hibernate Core 3.2.0GA and above.
  3. Download and add the Hibernate-Annotations jar file in the project workspace.

First Application :

First of all you have to create a table "employee". Which has only two columns i.e ID and Name. In hibernate core to achieve the mapping for the "employee" table the user should create the following files :

  1. Utility file for configuring and building the session factory.
  2. Hibernate.cfg.xml or any other Datasource metadata file
  3. Employee POJO object.
  4. Note: employee.hbm.xml file. (This file is now omitted for the )
  5. Real application file which has the actual logic manipulate the POJO

Note: Annotations are only the step to remove the employee.hbm.xml file so all the steps remain same only some modifications in some part and adding the annotation data for the POJO.

Please note that coming example will use the "employee" table from the database. The SQL query to create the employee table is as follows :

Table Name: employee

CREATE TABLE `employee` ( 
`id` int(11) NOT NULL, 
`name` varchar(20) default NULL, 
PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Follows the following steps for developing the hibernate annotation application.

Step 1:- Creating Utility Class :- The following is the code given for the utility class for sessionFactory: package net.roseindia;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
  
  private static final SessionFactory sessionFactory;
  static {
  try {
  // Create the SessionFactory from hibernate.cfg.xml
  sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
  } catch (Throwable ex) {
  // Make sure you log the exception, as it might be swallowed
  System.err.println("Initial SessionFactory creation failed." + ex);
  throw new ExceptionInInitializerError(ex);
  }
  }

  public static SessionFactory getSessionFactory() {
  return sessionFactory;
  }

}

If you see the only change in the file for the annotations is we use AnnotationConfiguration() class instead of the Configuration() class to build the sessionFactory for the hibernate.

Step 2: - The hibernate.cfg.xml is the configuration file for the datasource in the Hibernate. This configuration file contains (a.) database connection setting (database driver (com.mysql.jdbc.Driver), url (jdbc:mysql://192.168.10.83/hibernateannotation), username (deepak) and password (deepak)), (b.) SQL dialect (dialect - org.hibernate.dialect.MySQLDialect), (c.) enable hibernate's automatic session context management (current_session_context_class - thread), (d.) disable the second level cache (cache.provider_class - org.hibernate.cache.NoCacheProvider), (e.) print all executed SQL to stdout (show_sql - true)and (f.) drop and re-create the database schema on startup (hbm2ddl.auto - none). 

The following is the example for the configuration file.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.10.83/hibernateannotation</property>
<property name="connection.username">deepak</property>
<property name="connection.password">deepak</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">none</property>

<mapping class="net.roseindia.Employee"/>

</session-factory>
</hibernate-configuration>

The only change is, we are now telling the compiler that instead of any resource get the metadata for the mapping from the POJO class itself like in this case it is net.roseindia.Employee .

Note:- Using annotations does not mean that you cannot give the hbm.xml file mappng. You can mix annotations and hbm.xml files mapping for different Pojo but you cannot mix the mappings for the same Pojo in both ways. This we will discuss further.

Step 3: -The major changes occurred only in the POJO files if you want to use the annotations as this is the file which will now contain the mapping of the properties with the database.

The following is the code for the Employee POJO.

package net.roseindia;

import java.io.Serializable;

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

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
  public Employee() {

  }
  @Id
  @Column(name = "id")
  Integer id;

  @Column(name = "name")
  String name;

  public Integer getId() {
  return id;
  }

  public void setId(Integer id) {
  this.id = id;
  }

  public String getName() {
  return name;
  }

  public void setName(String name) {
  this.name = name;
  }

}

In the EJB word the entities represent the persistence object. This can be achieved by @Entity at the class level. @Table(name = "employee") annotation tells the entity is mapped with the table employee in the database. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance. The @Id element defines the mapping from that property to the primary key column. @Column is used to map the entities with the column in the database.

Step 4: -The following code demonstrate storing the entity in the database. The code is identical as you have used in the Hibernate applications.

package net.roseindia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class Example1 {
  
  public static void main(String[] argsthrows Exception {
  /** Getting the Session Factory and session */
  SessionFactory session = HibernateUtil.getSessionFactory();
  Session sess = session.getCurrentSession();
  /** Starting the Transaction */
  Transaction tx = sess.beginTransaction();
  /** Creating Pojo */
  Employee pojo = new Employee();
  pojo.setId(new Integer(5));
  pojo.setName("XYZ");
  /** Saving POJO */
  sess.save(pojo);
  /** Commiting the changes */
  tx.commit();
  System.out.println("Record Inserted");  
  /** Closing Session */
  session.close();
  }

}

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into employee (name, id) values (?, ?)
Record Inserted

Then you get: