×
DocsConsole

DocsConsole

Hibernate 5 Basic Example (With XML)

By | | Updated : 2018-10-20 | Viewed : 339 times

Hibernate 5 Basic Example (With XML)

We will try to create Hibernate Environment Setup. With Created Setup we will write and execute one Hibernate Basic Example.

    Prerequisites

  • Java 1.8

  • Eclipse 4.8.0

  • Maven 3.5.4

Hibernate Environment Setup

After installation Java 1.8, we have to set up eclipse. For maven installation please click here.Maven is already setup with in eclipse. So we can create the application eclipse contained maven. Or if you want you can install separately.

After installation Java 1.8, we have to set up eclipse. For maven installation please click here.Maven is already setup with in eclipse. So we can create the application eclipse contained maven. Or if you want you can install separately.

Hibernate Basic Example

Database Setup
CREATE DATABASE IF NOT EXISTS `docsconsole`;


CREATE TABLE IF NOT EXISTS `employees` (
  `emp_id` int(11) DEFAULT NULL,
  `emp_first_name` varchar(50) DEFAULT NULL,
  `emp_last_name` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `employees` (`emp_id`, `emp_first_name`, `emp_last_name`) VALUES
(101, 'Raj', 'Madav'),	(102, 'Ram', 'Dev');

Please follow below given steps in eclipse to create the Maven Java Project.

Click on File tab 
--> New 
--> Click on Maven Project 
--> Please check on Create Simple Project (Skip architype selection) 
--> Click on Next --> Enter the values docs.console.hibernate.com as Group Id, HibernateFirstExample as Artifact Id 
--> Click on Finish

Note: Packaging should be jar.

Now we have created the Maven Java Project successfully.

Next is creating the domain/entity class for employees table.

Right click on src/main/java 
--> New 
--> Click on Class 
--> Enter value for Package as docs.console.hibernate.com.model and Enter value for Name Employee.

Please write the below given code for Employee.java

Employee .java

package docs.console.hibernate.com.model;

public class Employee {
	
	private static final long serialVersionUID = 1L;

	private Integer empId;
	private String empFirstName;
	private String EmpLastName;

	public Employee() {
	}

	public Employee(Integer empId, String empFirstName,String EmpLastName) {
		this.empId = empId;
		this.empFirstName = empFirstName;
		this.EmpLastName = EmpLastName;
	}

	public Integer getEmpId() {
		return empId;
	}

	public void setEmpId(Integer empId) {
		this.empId = empId;
	}

	public String getEmpFirstName() {
		return empFirstName;
	}

	public void setEmpFirstName(String empFirstName) {
		this.empFirstName = empFirstName;
	}

	public String getEmpLastName() {
		return EmpLastName;
	}

	public void setEmpLastName(String empLastName) {
		EmpLastName = empLastName;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	
}

We will update pom.xml to get required dependency jar files.

pom.xml
<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>docs.console.hibernate.com</groupId>
	<artifactId>HibernateFirstExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<hibernate-core-version>5.3.7.Final</hibernate-core-version>
		<mysql.connector.version>6.0.5</mysql.connector.version>
	</properties>

	<dependencies>


		<!-- Hibernate 5.2.6 Final -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.3.7.Final</version>
		</dependency>

		<!-- MySql Driver -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.connector.version}</version>
		</dependency>
	</dependencies>

	<!-- Maven Compiler Plugin -->
	<build>
		<sourceDirectory>src/main/java</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Now we will create configuration file for hibernate.

Right click on src/main/resources 
--> New 
--> Click on Other 
--> select XML File 
--> Click Next 
--> Enter value for File Name hibernate.cfg.xml

Please add below given xml tags to the hibernate.cfg.xml.

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>
		<!-- Database connection settings -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost/docsconsole</property>
		<property name="connection.username">root</property>
		<property name="connection.password"></property>
		
		<!-- JDBC connection pool (use the built-in) -->
		<property name="connection.pool_size">1</property>
		
		<!-- SQL dialect -->
		<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
		
		<!-- Enable Hibernate's automatic session context management -->
		<property name="current_session_context_class">thread</property>
		
		<!-- Disable the second-level cache -->
		<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
		
		<!-- Echo all executed SQL to stdout -->
		<property name="show_sql">true</property>
		
		<!-- Drop and re-create the database schema on startup -->
		<property name="hbm2ddl.auto">update</property>
		<mapping resource="docs/console/com/Employee.hbm.xml" />
	</session-factory>
	
</hibernate-configuration>

Next step we will create class HibernateMainClient

Right click on src/main/java 
--> New 
--> Click on Class 
--> Enter value for Package as docs.console.hibernate.com and Enter value for Name HibernateMainClient

Please find below given code for HibernateMainClient.java.

HibernateMainClient.java

package docs.console.hibernate.com;
import java.util.List;

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

import docs.console.hibernate.com.util.HibernateUtil;

public class HibernateMainClient {

	
	static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	static final String DB_URL = "jdbc:mysql://localhost/docsconsole";

	static final String USERNAME = "root";
	static final String PASSWORD = "";

	public static void main(String[] args) {
		
		System.out.println("::::::::::::::::--------------------Started main method here-------------------::::::::::::::::");

		SessionFactory sfactory = HibernateUtil.getSessionFactory();
		System.out.println("::::::::::::::::--------------------SessionFactory is created here-------------------::::::::::::::::");
		Session session = sfactory.getCurrentSession();
		Transaction tx = session.beginTransaction();
		System.out.println("::::::::::::::::--------------------Transaction is created here-------------------::::::::::::::::");
		Query query = session.createSQLQuery("select emp_id, emp_first_name, emp_last_name FROM employees");
		List resultList = query.list();
		
		for(Object object: resultList){
			Object[] objectArray =(Object[])object;
			System.out.println("::::::::::::::::--------------------Employe Id:"+objectArray[0]);
			System.out.println("::::::::::::::::--------------------Employe First Name:"+objectArray[1]);
			System.out.println("::::::::::::::::--------------------Employe Last Name:"+objectArray[2]);
		}
		tx.commit();
		
	}
}

Create hbm file for Employee entity class.

Right click on docs.console.hibernate.com 
--> New 
--> Click on Other 
--> select XML File 
--> Click Next 
--> Enter value for File Name Employee.hbm.xml

Below xml content for Employee.hbm.xml

Employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="docs.console.com.model.Employee" table="employees"
		catalog="docsconsole">
		<id name="empId" type="java.lang.Integer">
			<column name="emp_id" />
			<generator class="identity" />
		</id>
		<property name="empFirstName" type="string">
			<column name="emp_first_name" length="10" not-null="true"
				unique="true" />
		</property>
		<property name="EmpLastName" type="string">
			<column name="emp_last_name" length="20" not-null="true"
				unique="true" />
		</property>
	</class>
</hibernate-mapping>

Now we will create file for HibernateUtil.java

Right click on src/main/java 
--> New 
--> Click on Class 
--> Enter value for Package as docs.console.hibernate.com.util and Enter value for Name HibernateUtil.

Please find below given code for HibernateUtil.java.

HibernateUtil.java
package docs.console.hibernate.com.util;

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

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		
		try {
			
			// Create the SessionFactory from hibernate.cfg.xml
			return new Configuration().configure().buildSessionFactory();
		}
		catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

After creating the project the final architecture will be as given below.

Hibernate Hello world

When we execute the HibernateMainClient we will get below given output.

Hibernate Hello World Result

Download Source Code HibernateFirstExample.zip

Leave A Reply