Hibernate 4 Hello World

In this article, we will create a basic hibernate 4 project using Maven.

 

We will connect to a MySQL database, create an Employee table and add a record using Hibernate.

 

Here are the steps required for this :

  • Create an empty maven project
  • Add Hibernate dependency and MySQL dependency in pom.xml
  • Create a hibernate.cfg.xml containing db configurations
  • Create Employee class
  • Create utility class HibernateUtil to add the Employee record
  • Run the HibernateUtil class

 

Step 1 : (Create empty maven project)

We will use basic Maven archetype to build a simple project first. For this run below command :

 

mvn archetype:generate –DgroupId=com.topjavatutorial.app –DartifactId=HibernateDemo–DarchetypeArtifactId=maven–archetype–quickstart –DinteractiveMode=false
 
This command will create a java project with HibernateDemo at current path.

 
If you are looking for help on maven installation or understanding, the following post might be a good starting point:
 
Maven Basics
 

Step 2 : (Add needed dependencies)

 

Let’s go inside the project home HibernateDemo and hibernate 4 dependency in pom.xml

 

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>4.3.10.Final</version>

</dependency>

 

Since we will be connecting to MySQL database using hibernate, we would also need to specify the dependency for adding a MySQL driver.

 

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>5.1.34</version>

</dependency>

 

You should change the version number above to the version of MySQL you are using.

 

Here is how the pom.xml looks now :

 

<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.topjavatutorial</groupId>
  <artifactId>HibernateDemo</artifactId>
  <packaging>jar</packaging>
  <version>1.0</version>
  <name>HibernateDemo</name>
  <url>http://maven.apache.org</url>
  <dependencies>
   <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.34</version>
  </dependency>
   <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-core</artifactId>
     <version>4.3.10.Final</version>
    </dependency>
    <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-search-orm</artifactId>
     <version>5.3.0.Final</version>
  </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

 

Step 3: (Create a hibernate.cfg.xml containing db configurations)

 

Now under com.topjavatutorial package in src/main/java, lets add the configuration file 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 name=“”>

<property name=“hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>

<property name=“hibernate.connection.password”>password</property>

<property name=“hibernate.connection.url”>jdbc:mysql://localhost:3306/databasename</property>

<property name=“hibernate.connection.username”>user</property>

<property name=“hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>

<property name=“hibernate.show_sql”>true</property>

<property name=“hibernate.format_sql”>true</property>

<property name=“hibernate.hbm2ddl.auto”>create</property>

<mapping class=“com.techkatak.Employee”/>

</session-factory>

</hibernate-configuration>

 
Replace the connection url, userid and password fields corresponding to your MySQL database configuration.

 

If you decide to use another database like Oracle, Sybase, Microsoft Sql Server etc, then the driver_class and dialect would change accordingly.

 

In the property hibernate.hbm2ddl.auto, we have provided the value of “create”. This would create the table in database when the program is run.

 

The show_sql property would display the queries being executed in the console or log file.

 

We have also referred a class “Employee” in the mapping element. Now, lets create the Employee class.

 

Step 4 : (Create Employee class)

The employee class is a POJO with the annotations to identify this as a hibernate entity class.

 

package com.topjavatutorial;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private int id;
  private String name;
  private int age;
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  
}


 

Step 5 : (Create utility class HibernateUtil to add the Employee record)

 

 

Till now, we have created the configuration file and defined the entity that needs to be persisted. Now lets create the utility class that would read this configuration file, create a transaction and insert a record to the employee table in database.

 

We will create a Session object that would represent a communication between our java code and the database. The Session object would be used to create a transaction object using which we can insert the data.

 

Here is how the code would look like :

 

package com.topjavatutorial;

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

public class HibernateUtil {

  public static void main(String[] args) {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
        
    SessionFactory sessionFactory = configuration.buildSessionFactory();
    
    Session session = sessionFactory.openSession();
    Transaction trn = session.beginTransaction();
    
    Employee employee= new Employee();
    employee.setName("First Employee");
    employee.setAge(20);
    
    session.persist(employee);
    trn.commit();
    session.close();;
  }

}


 

 Step 6 : (Run the HibernateUtil class)

Now, if we run this HibernateUtil class in Eclipse, here is how the console log looks like :

 

console

 

 

Now, if we query the MySQL database, we should be able to see the data in the employee table.

 

mysql

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags