×
DocsConsole

DocsConsole

Hibernate 5 Basic Example (With Annotations)

By | | Updated : 2019-06-08 | Viewed : 441 times

Hibernate 5 Basic Example (With Annotations)

Here we are leaning here hibernate basic example with annotations. Annotations is another way of configuring the data. We will learn here how to configure the annotation.

    Prerequisites

  • Java 1.8

  • Eclipse 4.8.0

  • Maven 3.5.4

  • Mysql-5.7.19

  • Hibernate 5.3

Hibernate 5 Basic Example (With Annotations)

In creating Hibernate 5 Basic Example we will have to create maven project. We can create Maven project in eclipse as well as command prompt. Please follow below given steps to create Maven project in eclipse. First we will create the required tables then we can create the maven project.

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');
Creating Maven Project in Eclipse
Click on File tab 
--> New 
--> Click on Maven Project 
--> Please check on Create Simple Project (Skip architype selection) 
--> Click on Next --> Enter the values com.docsconsole.hibernate as Group Id, HibernateBaiscExample as Artifact Id 
--> Click on Finish

Please updated pom.xml given below.

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>com.docsconsole.hibernate</groupId>
	<artifactId>HibernateBaiscExample</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>

Please use below given steps and create the hibernate.cfg.xml file. The code for this xml file will be shown below.

Creation of hibernate.cfg.xml
Right click on src/main/resources 
--> New 
--> Click on Other 
--> select XML File 
--> Click Next 
--> Enter value for File Name hibernate.cfg.xml
hibernate.cfg.xml
<?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>
		<!-- 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>		
		
		<!-- Echo all executed SQL to stdout -->
		<property name="show_sql">true</property>		

		<mapping class="com.docsconsole.hibernate.model.Employee" />
	</session-factory>
	
</hibernate-configuration>

Here we have configured some of properties for Database connection. Some of them used for mapping mechanism and others will be used for logging the results.

Now we will create the Domain/Entity class used for mapping in bootstrap time.

Creation of Employee.java
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.
Employee.java

package com.docsconsole.hibernate.model;

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


@Entity
@Table( name = "EMPLOYEES" )
public class Employee {
	
	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "EMP_ID")	
	private Integer empId;
	
	@Column(name = "EMP_FIRST_NAME")
	private String empFirstName;
	
	@Column(name = "EMP_LAST_NAME")
	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;
	}

	
}

    Code Observations

  • @Entity specifies that the class is an entity.

  • @Table specifies the primary table for the annotated entity.

  • @ID specifies the primary key of an entity.

  • @Column specifies that the class is an entity.

Please find below given code for HibernateMainClient.java

HibernateUtil.java
package com.docsconsole.hibernate.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import com.docsconsole.hibernate.model.Employee;

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

	private static SessionFactory buildSessionFactory() {

		try {

			StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
					.configure("hibernate.cfg.xml").build();
			Metadata metadata = new MetadataSources(standardRegistry).addAnnotatedClass(Employee.class)
					.addAnnotatedClassName("com.docsconsole.hibernate.model.Employee").getMetadataBuilder()
					.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE).build();
			SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
			return sessionFactory;
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

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

Here new bootstrapping technique is used. If you observed earlier article, we used legacy bootstrapping. Due to drawbacks of legacy bootstrapping, new bootstrapping technique will be introduced.

Hibernate Bootstrapping:

In Bootstrapping, Hibernate will create the SessionFactoryby reading the hibernate-cfg.xml file. After that mapping mechanism will be started by reading Entity class/hbm.xml. We can use this SessionFactoryto create the session which will be used for curd operations from hibernate.

To test the above example we need a client. So we will write HibernateMainClient.java for execution.

HibernateMainClient.java

package com.docsconsole.hibernate;
import java.util.List;

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

import com.docsconsole.hibernate.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();
		
	}
}

The created project structure will be as given below.

Hibernate 5 Basic Example annotation

Please compile and exicute the HibernateMainClient.java. then you will get below given out put.

Hibernate 5 Basic Example annotation

Download Source Code HibernateBaiscExample.zip

Leave A Reply