Hibernate Hello World example using Annotation

In this tutorial we will write a CRUD application in Hibernate using Java 5 Annotation. For this we will use our previous tutorial Hibernate Maven MySQL hello world example (XML Mapping) as base and convert it from XML Mapping to Annotation.

Tools and Technologies used:

  1. Java JDK 5 or above
  2. Eclipse IDE 3.2 or above
  3. Maven 3.0 or above
  4. Hibernate 3.0 or above
  5. MySQL 5.0 or above

1. Database Creation

For this tutorial, we will create a simple table “employee” in MySQL. Use following script to create the table.

CREATE TABLE `employee` (
    `id` BIGINT(10) NOT NULL AUTO_INCREMENT,
    `firstname` VARCHAR(50) NULL DEFAULT NULL,
    `lastname` VARCHAR(50) NULL DEFAULT NULL,
    `birth_date` DATE NOT NULL,
    `cell_phone` VARCHAR(15) NOT NULL,
    PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=606

2. Create Project Structure

Follow the steps in Hibernate Maven MySQL hello world example (XML Mapping) to create project structure.

Or you can directly download the source code from above tutorial in Eclipse.

Download: HibernateHelloWorldXML.zip (8 kb)

3. Update Hibernate dependency in Maven pom.xml

We are going to use Annotation mapping in Hibernate. Update the maven’s pom.xml file and add following dependencies.

<?xml version="1.0" encoding="UTF-8"?><project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>HibernateCache</groupId>
  <artifactId>HibernateCache</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <description></description>
  <dependencies>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>ejb3-persistence</artifactId>
      <version>1.0.1.GA</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-annotations</artifactId>
      <version>3.3.1.GA</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.10</version>
    </dependency>
  </dependencies>
</project>

Once we update the Hibernate dependency, run following command in your project folder to update classpath in eclipse to that errors are removed.

mvn eclipse:eclipse


4. Delete unused Employee.hbm.xml

The Employee.hbm.xml file under /src/main/java/net/viralpatel/hibernate is no more required. Delete this file from project.

5. Update Employee entity

The Employee class is simple POJO. We will add Annotations in this class. Update it as follows:

package net.viralpatel.hibernate;

import java.sql.Date;

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

@Entity
@Table(name="EMPLOYEE")
public class Employee {

	@Id
	@GeneratedValue
	private Long id;

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

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

	@Column(name="birth_date")
	private Date birthDate;

	@Column(name="cell_phone")
	private String cellphone;

	public Employee() {

	}

	public Employee(String firstname, String lastname, Date birthdate, String phone) {
		this.firstname = firstname;
		this.lastname = lastname;
		this.birthDate = birthdate;
		this.cellphone = phone;

	}

	// Getter and Setter methods
}

6. Update Hibernate Utility

In our previous example, we were using Configuration class to generate SessionFactory object. In HibernateUtil we had following line of code:

return new Configuration()
            		.configure()
                    .buildSessionFactory();

Change this line and use AnnotationConfiguration instead of Configuration(). Replace this line with below code.

// import org.hibernate.cfg.AnnotationConfiguration;

return new AnnotationConfiguration()
            		.configure()
                    .buildSessionFactory();


7. Update Hibernate Configuration file

The hibernate.cfg.xml configuration file needs to be changed to add the new Annotation based entity class Employee.java instead of old XML Mapping Employee.hbm.xml.

Open /src/main/resources/hibernate.cfg.xml and replace following line:

<mapping resource="net/viralpatel/hibernate/Employee.hbm.xml"/>

Replace above line with following:

<mapping class="net.viralpatel.hibernate.Employee"/>


8. Review Final Project Structure

Review your project structure. It should be like:
hibernate-annotation-hello-wold-project-structure


9. Execute project

Execute the Main.java class and see output.

******* READ *******
Total Employees: 200
******* WRITE *******
201 Jack Bauer
******* UPDATE *******
Name Before Update:Paula
Name Aftere Update:James
******* DELETE *******
Object:null


That’s All Folks

Today we saw how to write our first Hibernate hello world example using Annotations. We used Maven to generate Java project and added Hibernate dependencies into it. Also we saw how to do different CRUD operations in Hibernate.

Download Source

HibernateHelloWorldAnnotation.zip (15 kb)



One Comment

  • Karthik wrote on 16 December, 2011, 17:56

    Awesome Tutorial.
    In pom.xml, currently, the annotations, JPA etc.. are part of hibernate-core dependency.
    Please do update Dependencies in pom.xml to:
    (Remove extra “”). Some issues with posting comment here

    <>
    <>mysql<>
    <>mysql-connector-java<>
    <>5.1.18<>
    <>

    <>
    <>org.hibernate<>
    <>hibernate-core<>
    <>4.0.0.Final<>
    <>

    <>
    <>junit<>
    <>junit<>
    <>3.8.1<>
    <>test<>
    <>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Copyright © 2012 ViralPatel.net. All rights reserved.