SQL Zone is brought to you in partnership with:

Meyyappan has posted 101 posts at DZone. View Full User Profile

Hibernate Annotations Tutorial

06.14.2012
| 78814 views |
  • submit to reddit

This example is the same as the first example except that it uses annotations. There we first started by creating the .hbm.xml file, here there is no need to create it instead we will use annotations to do the object relational mapping.

In addition to the already existing jar files you need to add the following jar files to the classpath.

hibernate-commons-annotations.jar
ejb3-persistence.jar
hibernate-annotations.jar

Here we first start by creating the Course class. The Course class is shown below.

package com.vaannila.course;

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


@Entity
@Table(name="COURSES")
public class Course {

    private long courseId;
    private String courseName;
    
    public Course() {
    }
    
    public Course(String courseName) {
    this.courseName = courseName;
    }
    
    @Id
    @GeneratedValue
    @Column(name="COURSE_ID")
    public long getCourseId() {
    	return this.courseId;
    }
    
    public void setCourseId(long courseId) {
    	this.courseId = courseId;
    }
    
    @Column(name="COURSE_NAME", nullable=false)
    public String getCourseName() {
   		return this.courseName;
    }
    
    public void setCourseName(String courseName) {
    	this.courseName = courseName;
    }

}

As you can see we have used annotations in the code to do the object relational mapping. Hibernate supports EJB 3 persistence annotations. The EJB 3 annotations are contained in the javax.persistence package. If you avoid using Hibernate specific features in your application, then you will have the freedom to deploy your application in any environment that supports EJB 3. Anything imported from javax.persistence package tree is EJB 3 supported and anything imported from org.hibernate package tree is Hibernate specific.

The @Entity annotation is used to mark this class as an Entity bean. So the class should atleast have a package scope no-argument constructor.

The @Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If @Table annotation is not specified then Hibernate will by default use the class name as the table name.

The @Id annotation is used to specify the identifier property of the entity bean. The placement of the @Id annotation determines the default access strategy that Hibernate will use for the mapping. If the @Id annotation is placed over the field, then filed access will be used. Instead if it placed over the getter method of that field, then property access will be used. Here we use property access.

The @GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.

The @Column annotation is used to specify the details of the column to which a field or property will be mapped. Here the courseId property is mapped to COURSE_ID column in the COURSES table. If the @Column annotation is not specified by default the property name will be used as the column name.

The next change you need to do here is, instead of adding the .hbm.xml file to the hibernate.cfg.xml file, we add the fully qualified name of the annotated class to the mapping element.

<?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>
        <property name="hibernate.connection.driver_class"> org.hsqldb.jdbcDriver</property>
        <property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="connection.password"></property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.vaannila.course.Course" />
    </session-factory>
</hibernate-configuration>

The SessionFactory should be configured using the AnnotationConfiguration object instead of the Configuration object used with XML mappings.

package com.vaannila.util;

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

public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

These are the only few changes you need to do to make the example work using annotations. Now the big question is should you use annotations?

If your answer is yes to the following questions then you can use annotations in your project.

  • Do you have the flexibility to use Java 5 Environment?
  • Do you have the knowledge of which production database you are going to use? If yes, you can use annotations, this brings in strong coupling. Inorder to support multiple databases, it is better to have the mapping information in a seperate xml file rather than using annotations. You can easily have multiple xml files each specific for a particular database rather than having a different sets of source codes.

Instead than keeping the mapping informations in a seperate file, using annotations you can always keep them along with the source code, in this way the soure code and mapping information will always be in sync.

You can download the source code of this example by clicking the Download link below.

Source: Download
Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Sumit Sharma replied on Sun, 2012/12/23 - 2:27pm

can we use the hibernate annotation in above entity class like org.hibernate.annotations.Entity instead of javax.persistence.Entity


Abhishek Sharma replied on Wed, 2013/03/20 - 9:30am

yes we can use the hibernate annotation in above entity class.

Sumit Sharma replied on Thu, 2013/03/21 - 2:21am in response to: Abhishek Sharma

then what is the difference between these two different annotation and which one we should prefer?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.