Hibernate Annotation Tutorial

Hibernate Annotation Tutorial

This demo will show you how to use hibernate annotation and perform database CRUD option using MySQL data base. To keep this tutorial simple we will use only one table to insert and retrieve data from data base.

Tools needed:

  • Eclipse ( We are using eclipse Kepler) – Download from here
  • Install JBoss tools in eclipse. If you are not sure how to install JBoss in eclipse please user this URL:Install JBoss tools in eclipse
  • MySQL data base (Install MySQL Community Server (GPL) version in your system : MySQL Community Server). We are using version 5.6
  • Hibernate 3.2
  • Maven 3.2.1

Step 1: Create table in MySQL data base script:

CREATE TABLE address ( 
    Steet_Name  varchar(50) NULL,
    Location    varchar(25) NULL,
    City        varchar(25) NULL,
    Zip         varchar(25) NULL,
    State       varchar(25) NULL,
    id          int(11) NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (id)


Step 2. Eclipse project setup:

Note: We have generated domain code *.java, *.hbm.xml file, *.cfg.xml file from hibernate tools please follow this hibernate tutorial to generate all related files.

Step 3: Please copy below dependency to your pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <name>HibernateAnnotationExample Maven Webapp</name>

        <!-- MySQL database -->














Step 4: Below is final project structure:

Hibernate Annotation Tutorial

Step 5: hibernate.cfg.xml file don’t forget to replace your database configuration properties:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    <session-factory name="sessionFactory">
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">admin</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javahonk</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.search.autoregister_listeners">false</property>
        <property name="show_sql">true</property>
        <mapping class="com.javahonk.bean.Address" />

Step 6: Address.java – Copy paste in com.javahonk.bean package:

package com.javahonk.bean;

// Generated May 21, 2014 10:45:29 AM by Hibernate Tools 3.4.0.CR1

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

 * Address generated by hbm2java
@Table(name = "address", catalog = "javahonk")
public class Address implements java.io.Serializable {

    private Integer id;
    private String steetName;
    private String location;
    private String city;
    private String zip;
    private String state;

    public Address() {

    public Address(String steetName, String location, String city, String zip,
            String state) {
        this.steetName = steetName;
        this.location = location;
        this.city = city;
        this.zip = zip;
        this.state = state;

    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;

    public void setId(Integer id) {
        this.id = id;

    @Column(name = "Steet_Name", length = 50)
    public String getSteetName() {
        return this.steetName;

    public void setSteetName(String steetName) {
        this.steetName = steetName;

    @Column(name = "Location", length = 25)
    public String getLocation() {
        return this.location;

    public void setLocation(String location) {
        this.location = location;

    @Column(name = "City", length = 25)
    public String getCity() {
        return this.city;

    public void setCity(String city) {
        this.city = city;

    @Column(name = "Zip", length = 25)
    public String getZip() {
        return this.zip;

    public void setZip(String zip) {
        this.zip = zip;

    @Column(name = "State", length = 25)
    public String getState() {
        return this.state;

    public void setState(String state) {
        this.state = state;


Step 7: HibernateUtil – To create session factory copy paste below code inside com.javahonk package:

package com.javahonk;

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

public class HibernateUtil {
    private static final SessionFactory sessionFactory
                        = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            return new AnnotationConfiguration().configure()
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory "
                    + "creation failed." + ex);
            throw new ExceptionInInitializerError(ex);

    public static SessionFactory getSessionFactory() {
        return sessionFactory;

    public static void shutdown() {

Step 8: HibernateAnnotationTest.java – Test class to insert and retrieve data from data base:

package com.javahonk;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.javahonk.bean.Address;

public class HibernateAnnotationTest {
    public static void main(String[] args) {

        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();

        Address address=new Address();
        address.setSteetName("John st."); 


        List<Address> address3 = session.createQuery("from Address")
        for (Address address2 : address3) {
            System.out.println("Address table data:");
            System.out.println("Stree Name: "+address2.getSteetName()
                    +" Location: "+address2.getLocation()+" City: "
                    +address2.getCity()+" State: "+address2.getState()
                    +" Zip: "+address2.getZip());



Step 9: To run test class right click –> Run As –> Java Application . You will see below rows inserted in the table because in code we are inserting and retrieving data from data base:

Hibernate Annotation Tutorial

Step 10: Row inserted in data base:
Hibernate Annotation Tutorial


download2 Download project: HibernateAnnotationExample

That’s it Hibernate Annotation Tutorial

Leave a Reply

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

I am not Robot *