Saturday , August 19 2017
Home / Hibernate / Hibernate 4 Example with Annotations

Hibernate 4 Example with Annotations

Hibernate 4 Example

In this example we are going to work with Hibernate 4 and mySql 5.5.43. In the previous tutorial we have developed an entire CRUD application with Hibernate 5, But the example was developed by using the XML based configuration.

The present tutorial is for Hibernate 4 Example with annotation based configuration using maven.

For implementing the Hibernate Example we are going to use below Tools:

  • Hibernate-core 4.0
  • Mysql 5.5.43
  • NetBeans 8.0

Lets start the step by step CRUD Hibernate Example with Hibernate 4.

Setup Database:

For this tutorial, we are going to use mySql Database.

Create onlinetutorialspoint database and use  it.


mysql> create database onlinetutorialspoint;
 
mysql> use onlinetutorialspoint;

Then create a student table in onlinetutorialspoint database.


CREATE TABLE `student` (
    `id` INT(10) NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(50) NULL DEFAULT NULL,
    `rollnumber` INT(10) NULL DEFAULT NULL,
    `gender` TINYINT(4) NULL DEFAULT NULL,
    `class` VARCHAR(50) NULL DEFAULT NULL,
    `lastupdated` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`)
);

Project Structure:

Hibernate 4 AnntationsMaven Dependencies:


<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.onlinetutorialspoint</groupId>
    <artifactId>HibernateMaven</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <repositories>
    <repository>
      <id>JBoss repository</id>
      <url>http://repository.jboss.com/maven2/</url>
    </repository>
        <repository>
            <id>unknown-jars-temp-repo</id>
            <name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
            <url>file:${project.basedir}/lib</url>
        </repository>
    </repositories>
   <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>4.0.1.Final</version>
            <classifier>tests</classifier>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.1.8.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.1.0.CR2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.4</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.10</version>
        </dependency>
       <dependency>
           <groupId>mysql-connector</groupId>
            <artifactId>mysql-connector-java-5.1.23-bin</artifactId>
            <version>SNAPSHOT</version>
        </dependency>
    </dependencies>     
</project>
 

Above is the pom.xml, where we can define all required maven dependencies.

Create Hibernate Configuration:


<?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.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/onlinetutorialspoint?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">XYZ-ABC</property>
    <!--Here we are mapping Pojo class not hbm-->
     <mapping class="com.onlinetutorialspoint.pojo.Student" />
  </session-factory>
</hibernate-configuration>

Create Hibernate Utils:

Create HibernateConnector.java, from which we are getting Hibernate session and doing basic configurations.


package com.onlinetutorialspoint.config;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateConnector {

    private static HibernateConnector me;
    private Configuration cfg;
    private SessionFactory sessionFactory;

    private HibernateConnector() throws HibernateException {

        // build the config
        cfg = new Configuration().configure();
        
        sessionFactory = cfg.buildSessionFactory();
    }

    public static synchronized HibernateConnector getInstance() throws HibernateException {
        if (me == null) {
            me = new HibernateConnector();
        }

        return me;
    }

    public Session getSession() throws HibernateException {
        Session session = sessionFactory.openSession();
        if (!session.isConnected()) {
            this.reconnect();
        }
        return session;
    }

    private void reconnect() throws HibernateException {
        this.sessionFactory = cfg.buildSessionFactory();
    }
}

Create Pojo class with respect to the student table.

Student.java


package com.onlinetutorialspoint.pojo;

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;

@Entity
@Table(name = "student", catalog = "onlinetutorialspoint"
)
public class Student implements java.io.Serializable {

    private Integer id;
    private String name;
    private Integer rollnumber;
    private Byte gender;
    private String class_;

    public Student() {
    }

    public Student(String name, Integer rollnumber, Byte gender, String class_) {
        this.name = name;
        this.rollnumber = rollnumber;
        this.gender = gender;
        this.class_ = class_;
    }

    @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 = "name", length = 50)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "rollnumber")
    public Integer getRollnumber() {
        return this.rollnumber;
    }

    public void setRollnumber(Integer rollnumber) {
        this.rollnumber = rollnumber;
    }

    @Column(name = "gender")
    public Byte getGender() {
        return this.gender;
    }

    public void setGender(Byte gender) {
        this.gender = gender;
    }

    @Column(name = "class", length = 50)
    public String getClass_() {
        return this.class_;
    }

    public void setClass_(String class_) {
        this.class_ = class_;
    }

}

On the above pojo class, we are using some basic annotations like @Entity, @Table, @Id, @GeneratedValue, @Column. As this example developed by using annotations, we need to know the purpose of each annotation. All annotations comes from  javax.persistence package.

@Entity

@Entity is an EJB 3 standard  annotation, used to specify the class is an entity. By using this annotation we are going to tell the hibernate, treat this class as an Entity.

@Table

@Table annotation comes from  javax.persistence, used to specify the primary table to the annotated Entity. We do configure the secondary tables too, by using the @SecondaryTable annotation.

@Id and @GeneratedValue

In hibernate, each entity will have the primary key or keys (composite). We can configure the primary keys by using the @id annotation. The type of the particular primary key will be defined as @GeneratedValue. The @GeneratedValue may be applied for primary keys or fields of an entity or mapped super classes in conjunction with id attribute. For more generators in hibernate.

@Column

@Column annotation is used to specify the mapped column with persistent property.

 Note: No need to create “hbm.xml” file w.r.t the pojo class and database table, as this is an annotation based example.

Create Data Access Object (DAO)

Create StudentDAO.java to access the Student details.


package com.onlinetutorialspoint.dao;

import com.onlinetutorialspoint.config.HibernateConnector;
import com.onlinetutorialspoint.pojo.Student;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class StudentDAO {

    public List<Student> listStudent() {
        Session session = null;
        try {
            session = HibernateConnector.getInstance().getSession();
            Query query = session.createQuery("from Student s");

            List queryList = query.list();
            if (queryList != null && queryList.isEmpty()) {
                return null;
            } else {
                System.out.println("list " + queryList);
                return (List<Student>) queryList;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            session.close();
        }
    }

    public Student findStudentById(int id) {
        Session session = null;
        try {
            session = HibernateConnector.getInstance().getSession();
            Query query = session.createQuery("from Student s where s.id = :id");
            query.setParameter("id", id);

            List queryList = query.list();
            if (queryList != null && queryList.isEmpty()) {
                return null;
            } else {
                return (Student) queryList.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            session.close();
        }
    }

    public void updateStudent(Student student) {
        Session session = null;
        try {
            session = HibernateConnector.getInstance().getSession();
            session.saveOrUpdate(student);
            session.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    public Student addStudent(Student student) {
        Session session = null;
        Transaction transaction = null;
        try {
            session = HibernateConnector.getInstance().getSession();
            System.out.println("session : "+session);
            transaction = session.beginTransaction();
            session.save(student);
            transaction.commit();
            return student;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void deleteStudent(int id) {
        Session session = null;
        try {
            session = HibernateConnector.getInstance().getSession();
            Transaction beginTransaction = session.beginTransaction();
            Query createQuery = session.createQuery("delete from Student s where s.id =:id");
            createQuery.setParameter("id", id);
            createQuery.executeUpdate();
            beginTransaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

}

Hibernate Client

Create a client class, from which we can access the StudentDAO.java to make CRUD operations.


package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.dao.StudentDAO;
import com.onlinetutorialspoint.pojo.Student;
import java.util.List;

public class DbOperations {

    StudentDAO studentDAO = new StudentDAO();

    public static void main(String[] args) {
        DbOperations dbOperations = new DbOperations();
        Student createStudent = dbOperations.createStudent();

        List<Student> studentList = dbOperations.getStudentList();
        if (studentList != null) {
            for (Student student : studentList) {
                System.out.println("Student Name : " + student.getName());
            }
        }
        dbOperations.updateStudent(createStudent.getId());
        Student student = dbOperations.getStudent(createStudent.getId());
        if (student != null) {
            System.out.println("Student Details After Updation : " + student.getName());
        }

        dbOperations.deleteStudent(createStudent.getId());

    }

    public Student createStudent() {
        Student s = new Student();
        s.setGender(new Byte("1"));
        s.setName("smith");
        s.setClass_("12");
        s.setRollnumber(007);
        studentDAO.addStudent(s);
        return s;
    }

    public void updateStudent(Integer id) {
        Student student = studentDAO.findStudentById(id);
        student.setName("online tutorials point");
        studentDAO.updateStudent(student);
        System.out.println("Student Updated Success");
    }

    public void deleteStudent(Integer id) {
        studentDAO.deleteStudent(id);
        System.out.println("Student Deleted Success");
    }

    public List<Student> getStudentList() {
        return studentDAO.listStudent();
    }

    public Student getStudent(Integer id) {
        return studentDAO.findStudentById(id);
    }

}

Output :

Student Name : smith
Student Updated Success
Student Details After Updation : online tutorials point
Student Deleted Success

Download Example

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

Hibernate Native SQL Query Example

In this tutorials, we are going to learn about Hibernate Native SQL with example. Hibernate …

One comment

  1. kiran@gmail.com'

    Nice article

Leave a Reply

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