Frameworks| Hibernate| Struts| JSF| JavaFX| Ajax| Spring| DOJO| JDO| iBatis| Questions?

Hot Searches
struts-config.xml  web.xml  Java date format  read/write text file using javascript  ArrayList  Insert Data into Database Using Hibernat  create text file using java  insert data to text file using java  Visual Basic Date and Time Display the t  Create table and insert data by sql quer 

  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

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 theHibernate 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[] 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 :-

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.

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

4 comments so far (
post your own) View All Comments Latest 10 Comments:

pls provide name of the jars to be used and where they can be downloaded from.

Posted by novacancy123 on Saturday, 12.13.08 @ 10:13am | #82718

Wonderful Work RoseIndia !
Thanks !

Posted by Nis on Thursday, 10.30.08 @ 12:51pm | #81411

Hi, i was follow your tutorial and download your code. I can compile, create schema based from your code. But, when i run your code, i've got problem at HibernateUtil.java :
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

Error like this :
-------------------------------------------------
Exception in thread "Main Thread" java.lang.ExceptionInInitializerError
at com.HibernateUtil.<clinit>(HibernateUtil.java:11)
at com.Example1.main(Example1.java:14)
Caused by: org.apache.commons.logging.LogConfigurationException: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException) (Caused by org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException))
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:543)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:235)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:209)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:351)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:120)
... 2 more
Caused by: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException)
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:397)
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:529)
... 6 more
Caused by: java.lang.NullPointerException
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:374)
... 7 more
-------------------------------------------------

Can you help me to solve this problem ?

Thanks,
Hendra

Posted by Hendra on Saturday, 01.5.08 @ 12:32pm | #44557

VERY GOOD ARTICLE

Posted by GAJENDRA on Tuesday, 08.21.07 @ 16:07pm | #23843

Tell A Friend
Your Friend Name

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.