Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Hibernate Hibernateannotations Quick Hibernate Annotation Tutorial

Related Tutorials


 
 

Share on Google+Share on Google+

Quick Hibernate Annotation Tutorial

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

Hibernate Annotations

     

Note:- This tutorial covers only the Annotations part. The reader must have hands on experience before starting this tutorial.

Introduction:- 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 (Tiger) 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.The First Application :-

Let us assume we have a table Employee which has only two columns i.e ID and Name. In hibernate core to achieve the mapping for the above 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. 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 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 :-

Create table Employee( 
ID int2 PRIMARY KEY, 
NAME nvarchar(30) ); 

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 Configuratio() class to build the sessionFactory for the hibernate.

Step 2: - The Hibernate.cfg.xml is the configuration file for the datasource in the Hibernate world. 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://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</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="com.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 {

  /**
 * @param args
 */
  public static void main(String[] args) throws 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 :-

Record Inserted.

Download this Example Code.

Conclusion:-

The above article shows the basic configurations for the Hibernate annotations. The above example will only add one record in the Database using the hibernate annotations. In the coming article we will discuss about the various available annotations in the JPA and the also the examples demonstrate how to use the annotations for mapping all the hibernate POJO to the database tables.

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 11, 2008

Related Tutorials

Discuss: Quick Hibernate Annotation Tutorial   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:3
daori
November 2, 2011
thanks

good article. thanks
yesu
March 7, 2012
Very Bad

What i ask? what you show? How much bad this is? Is this is your service? very very Bad man. Try to change or just close your service pls.
Ahmed Adel
April 9, 2012
Thanks

Thanks this is very useful
DMCA.com