Hibernate 5 Hello World

In this article we are going to create Hello World application in Hibernate 5.

Hibernate 5 Hello World Example

In this section we will see how to create Hibernate 5 Hello World example. You will learn new API of Hibernate 5 and understand how to create session factory in this version of Hibernate. In Hibernate 5 session factory initialization process is different from Hibernate 4. You will learn the correct way to initialized Hibernate 5 session factory and then get session in your program.

In this Hibernate 5 Hello world program we are going to run query to get employee details from database and display on the console. We have used Eclipse and maven for easily project development. Use of maven will automatically download dependency jar files and include in the project.

Prerequisites to run Hibernate 5 Hello world program:

  • JDK 8 or above must be installed on your computer to use Hibernate 5.2 or above
  • Eclipse IDE is required
  • We are using MySQL database server as backend of application
  • Prior JDBC programming experience is necessary
  • SQL knowledge is necessary

Here is the video tutorial of "How to create Hibernate 4 Hello World Program?":

We have used the Eclipse IDE for coding and testing of the application. This is one of the first Hibernate 4 tutorial that you should learn first. In this tutorial I will teach you the process of creating your very first Hibernate example Step by Step.

Step 1: Download the Hibernate 5.2.x

You can download Hibernate 5 Hello world example code and import in Eclipse IDE (File--> Import --> Existing maven project).

We have used Maven in project and it downloads Hibernate 5 dependency. Here is code of 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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Hibernate5HelloWorld</groupId>
  <artifactId>Hibernate5HelloWorld</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
  
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.6</version>
	</dependency>
  
	  <dependency>
	    <groupId>org.hibernate</groupId>
	    <artifactId>hibernate-core</artifactId>
	    <version>5.2.8.Final</version>
	  </dependency>

  </dependencies>
  
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

We have used following dependency to include Hibernate 5 jars:

  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.8.Final</version>
  </dependency>
 

Step 2: Create database and table

Connect to MySQL server using any IDE or command line tool. Use the following query to create database:

create database hibernate5;

Now you should connect to database using following sql:

mysql> connect hibernate5;
Connection id:    3
Current database: hibernate5

mysql>

Use the following query to create the table:

CREATE TABLE `employee` (                      
            `id` int(11) NOT NULL AUTO_INCREMENT,        
            `emp_name` varchar(100) DEFAULT NULL,        
            `emp_address` varchar(500) DEFAULT NULL,     
            `emp_mobile_nos` varchar(100) DEFAULT NULL,  
            PRIMARY KEY (`id`)                           
          )

Step 3: Create model class

You should add the following code in the "Employee.java" file:

package net.roseindia;
import java.io.Serializable;

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

import javax.persistence.Table;
/**
 * @author Deepak Kumar
 * Web: http://www.roseindia.net
 */
@Entity
@Table(name = "employee")
public class Employee implements Serializable{

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

	@Column(name="emp_name")
	private String empName;

	@Column(name="emp_address")
	private String empAddress;	  

	@Column(name="emp_mobile_nos")
	private String empMobileNos;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public String getEmpAddress() {
		return empAddress;
	}

	public void setEmpAddress(String empAddress) {
		this.empAddress = empAddress;
	}

	public String getEmpMobileNos() {
		return empMobileNos;
	}

	public void setEmpMobileNos(String empMobileNos) {
		this.empMobileNos = empMobileNos;
	}

}

Step 4: Create hibernate.cfg file

Add the hibernate.cfg file ( create a new file in the src folder of eclipse) with the following code:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate5</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>

<mapping class="net.roseindia.model.Employee" />

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

Step 5: Create the utility class for getting SessionFactory

In Hibernate 5 API for creating session factory has changed. Here is full code of utility class:

package net.roseindia;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;


/**
* @author Deepak Kumar 
* Web: http://www.roseindia.net
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;

private static ServiceRegistry serviceRegistry;

static {
	try {
	StandardServiceRegistry standardRegistry = 
            new StandardServiceRegistryBuilder()
		.configure("hibernate.cfg.xml").build();
	Metadata metaData = new MetadataSources(
                   standardRegistry).getMetadataBuilder().build();
	sessionFactory = metaData.getSessionFactoryBuilder().build();
	} catch (Throwable th) {

		System.err.println("Enitial SessionFactory creation failed" + th);

		throw new ExceptionInInitializerError(th);

	}
}

public static SessionFactory getSessionFactory() {

	return sessionFactory;

}
}

In Hibernate 5 StandardServiceRegistry is used.

Step 6: Write the code for testing the Hello World Hibernate example.

Now we are ready to run our program. Following is full code of HibernateHelloWorld  class which contains main method and from here we are executing our Hibernate program.

Code:

package net.roseindia;

import java.util.Iterator;
import java.util.List;

import javax.persistence.criteria.CriteriaQuery;

import net.roseindia.model.Employee;

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

/**
 * @author Deepak Kumar 
 * * Web: http://www.roseindia.net
 */
public class HibernateHelloWorld {
public static void main(String[] args) throws Exception {

SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session session = sessFact.getCurrentSession();
org.hibernate.Transaction tr = session.beginTransaction();


/*
String strSql ="from Employee o";
Query query = session.createQuery(strSql);
List lst = query.list();
for(Iterator it=lst.iterator();it.hasNext();){

	Employee emp=(Employee)it.next();
	System.out.println("Hello: " + emp.getEmpName());
 }
  
*/

CriteriaQuery cq = session.getCriteriaBuilder().createQuery(Employee.class);
cq.from(Employee.class);
List employeeList = session.createQuery(cq).getResultList();

for (Employee employee : employeeList) {
	//System.out.println("ID: " + employee.getId());
	System.out.println("Hello: " + employee.getEmpName());
}  


tr.commit();
System.out.println("Data displayed");
sessFact.close();
}
}

In the above code you can see the old way of using query.

But we have used new method of Hibernate 5 to run query. Following code loads all data from database and prints Hello message with employee name:

CriteriaQuery<Employee> cq = session.getCriteriaBuilder().createQuery(Employee.class);
cq.from(Employee.class);
List<Employee> employeeList = session.createQuery(cq).getResultList();

for (Employee employee : employeeList) {
//System.out.println("ID: " + employee.getId());
System.out.println("Hello: " + employee.getEmpName());
}

In the above code we are display the message "Hello:" + Employee name.

So, you learned How to create Hibernate 5 Hello world program. Explore following tutorials of Hibernate 5:

Advertisements

Ads

 

We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.

Share on Google+Share on Google+

Hibernate 5 Hello World

Posted on: October 14, 2017 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Hibernate 5 Hello World  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads