Over a million developers have joined DZone.

Hibernate Annotations Tutorial

DZone's Guide to

Hibernate Annotations Tutorial

Free Resource

MongoDB Atlas is a database as a service that makes it easy to deploy, manage, and scale MongoDB. So you can focus on innovation, not operations. Brought to you in partnership with MongoDB.

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.


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;

public class Course {

    private long courseId;
    private String courseName;
    public Course() {
    public Course(String courseName) {
    this.courseName = courseName;
    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"
        <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" />

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

MongoDB Atlas is the best way to run MongoDB on AWS — highly secure by default, highly available, and fully elastic. Get started free. Brought to you in partnership with MongoDB.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}