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)
    )
GO

 

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">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javahonk</groupId>
    <artifactId>HibernateAnnotationExample</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>HibernateAnnotationExample Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- MySQL database -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>3.2.3.ga</version>
        </dependency>

        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>

        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.1</version>
        </dependency>

        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.5.0</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.3.0.ga</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>3.0.0.ga</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>HibernateAnnotationExample</finalName>
    </build>
</project>

 

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"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <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" />
    </session-factory>
</hibernate-configuration>

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
 */
@Entity
@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;
    }

    @Id
    @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()
                    .buildSessionFactory();
        } 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() {
        getSessionFactory().close();
    }
}

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();
        session.beginTransaction();

        Address address=new Address();
        address.setSteetName("John st."); 
        address.setLocation("NY");
        address.setCity("NY");
        address.setZip("123456");
        address.setState("NY"); 

        session.save(address); 

        List<Address> address3 = session.createQuery("from Address")
                .list();
        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());
            
        }

        session.getTransaction().commit();
        session.close();

    }
}

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 *