Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Saturday, 3 August 2013

Hibernate Hello World Example with Annotations - Create, Retrieve, Update and Delete operations in Hibernate

In our previous discussions we came across 'How to integrate Hibernate with Struts' and 'How to integrate Hibernate with Spring '. In this particular blog we will discuss how to perform basic CRUD (create, retrieve, update and delete) operations in hibernate using annotations. We will create a simple Java project with maven and w'll import that in Eclipse. Than we will add required pom.xml file to make it Hibernate project.

Our objective for today's discussion is to setup a Hibernate Maven project in eclipse and implement basic create, retrieve, update and delete operations with it.


Creating Database

Before we start lets create a simple database and table to apply hibernate operations on. Copy and Paste the following sql query in your query editor and execute.
-- Dumping database structure for userdb
CREATE DATABASE IF NOT EXISTS `userdb` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `userdb`;

I assumes that you are able to create a maven project and import that in eclipse, if not go through our previous discussion and setup a simple maven-java project before we go forward. Click Here


Adding required hibernate dependencies to pom.xml

Our very first step is to add all required hibernate dependencies to pom.xml, see the code below and add all required hibernate dependencies.
<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.beingjavaguys.hbn</groupId>
 <artifactId>HibernateMavenProject</artifactId>
 <packaging>jar</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>HibernateMavenProject</name>
 <url>http://maven.apache.org</url>
 <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.0.1.Final</version>
  </dependency>
  <dependency>
   <groupId>javax.validation</groupId>
   <artifactId>validation-api</artifactId>
   <version>1.0.0.GA</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.10</version>
  </dependency>
  </dependencies>
</project>


Now do a maven-install so that maven can download all specified hibernate dependencies for us.

C:\Users\nagesh.chauhan\maven-project\HibernateMavenProject>mvn install -Dmaven.
test.skip=true

Pleas make sure your Eclipse IDE is able to identify all maven repositories, if not follow the given steps to  add M2_REPO Manually.


Adding M2_REPO manually to Eclipse IDE

Follow the steps written below to make eclipse add all dependencies to project classpath.
1)  Go to Eclipse menu bar and select 'Window > Preferences'.
2)  Select Java > Build Path > Classpath Variables from left menu.
3)  Click on the new button > defined a new M2_REPO variable and point it to your local Maven repository
4)  Click Done button.

If everything goes right you will see all your dependencies added to class path like this.



Adding Hibernate configuration file (hibernate.cfg.xml)

HibernateMavenProject\resources\hibernate.cfg.xml

<?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="connection.url">jdbc:mysql://localhost:3306/userdb</property>
  <property name="connection.username">root</property>
  <property name="connection.password">root</property>
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

  <property name="show_sql">true</property>

  <property name="format_sql">true</property>
  <property name="hbm2ddl.auto">update</property>
  <property name="connection.pool_size">1</property>
  <property name="current_session_context_class">thread</property>

  <mapping class="com.beingjavaguys.hbn.User" />

 </session-factory>
</hibernate-configuration>


Adding Hibernate Utils class

This is a simple java class with a static method, we will use this class to get a session instance of hibernate session factory class.
package com.beingjavaguys.hbn;

/**
 * @author Nagesh Chauhan!
 * 
 */
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

 private static final SessionFactory sessionFactory = buildSessionFactory();

 private static SessionFactory buildSessionFactory() {
  try {
   return new Configuration().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();
 }

}


Adding domain class file

This is a simple pojo consisting of an user object, we will map this class to relational database using hibernate utilities.
package com.beingjavaguys.hbn;

/**
 * @author Nagesh Chauhan!
 * 
 */
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User {

 @Id
 @GeneratedValue
 @Column(name = "user_id")
 private int userId;

 @Column(name = "first_name")
 private String firstName;

 @Column(name = "last_name")
 private String lastName;

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

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

 public int getUserId() {
  return userId;
 }

 public void setUserId(int userId) {
  this.userId = userId;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getGender() {
  return gender;
 }

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

 public String getCity() {
  return city;
 }

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



Create (Insert) data in Hibernate

The code shown in below snippet specifies 'how to insert a row in database in hibernate'.
public void saveUser(User user) {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();

  session.save(user);

  session.getTransaction().commit();
 }


Retrieve (Read) data in Hibernate

The code shown in below snippet specifies 'how to read data from database in hibernate'.
public void getUser() {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();

  ArrayList<User> list = (ArrayList<User>) session.createQuery(
    "from User").list();
  if (list != null) {
   for (int i = 0; i < list.size(); i++) {
    System.out.println("User Data : " + list.get(i).getUserId());
    System.out.println("User First Name : "
      + list.get(i).getFirstName());
    System.out.println("User Last Name : "
      + list.get(i).getLastName());
    System.out.println("User Gender : " + list.get(i).getGender());
    System.out.println("User City : " + list.get(i).getCity());
   }
  }
  session.getTransaction().commit();
 }


Updating (Edit) data in Hibernate

The code shown in below snippet specifies 'how to update a row in database in hibernate'.
public void updateUser(User user) {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();

  session.merge(user);

  session.getTransaction().commit();
 }


Remove (Delete) data in hibernate

The code shown in below snippet specifies 'how to delete a row in database in hibernate'.
public void deleteUser(User user) {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();

  session.delete(user);

  session.getTransaction().commit();
 }


Implementation class code

This is simple java class containing main method to start execution, see the implementation to identify hibernate working in create, retrieve, update and delete operations.
package com.beingjavaguys.hbn;

import java.util.ArrayList;
import org.hibernate.Session;

/**
 * @author Nagesh Chauhan!
 * 
 */
public class App {
 public static void main(String[] args) {
  App app = new App();

  // create user data object
  User user = new User();
  user.setUserId(1);
  user.setFirstName("nagesh");
  user.setLastName("chauhan");
  user.setGender("male");
  user.setCity("gurgaon");

  User user1 = new User();
  user1.setUserId(2);
  user1.setFirstName("ankush");
  user1.setLastName("thakur");
  user1.setGender("male");
  user1.setCity("delhi");

  // save user in db
  app.saveUser(user);
  app.saveUser(user1);

  // update user data
  user.setCity("noida");
  app.updateUser(user);

  // delete user data
  app.deleteUser(user1);

  // get user data
  app.getUser();
 }

 public void saveUser(User user) {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();

  session.save(user);

  session.getTransaction().commit();
 }

 public void updateUser(User user) {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();

  session.merge(user);

  session.getTransaction().commit();
 }

 public void deleteUser(User user) {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();

  session.delete(user);

  session.getTransaction().commit();
 }

 public void getUser() {
  Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();

  ArrayList<User> list = (ArrayList<User>) session.createQuery(
    "from User").list();
  if (list != null) {
   for (int i = 0; i < list.size(); i++) {
    System.out.println("User Data : " + list.get(i).getUserId());
    System.out.println("User First Name : "
      + list.get(i).getFirstName());
    System.out.println("User Last Name : "
      + list.get(i).getLastName());
    System.out.println("User Gender : " + list.get(i).getGender());
    System.out.println("User City : " + list.get(i).getCity());
   }
  }
  session.getTransaction().commit();
 }
}



In this particular blog we came across ‘How to create a Hibernate Project in Maven’, 'Insert table in hibernate', 'Retrieve data from db in hibernate', 'Update a row in hibernate' and 'Delete data in hibernate'. In upcoming blogs we will see more about 'Maven', 'Hibernate', 'Java' and other Opensource Technologies.






Thanks for reading !
Being Java Guys Team

Download "Hibernate Hello World Example with Annotations Project" from "SkyDrive"





0 comments:

Post a Comment

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft