Hibernate Example With Annotations

By | | Updated : 2021-03-10 | Viewed : 1735 times

Hibernate 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.


  • 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

  `emp_id` int(11) DEFAULT NULL,
  `emp_first_name` varchar(50) DEFAULT NULL,
  `emp_last_name` varchar(50) DEFAULT NULL

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.

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">



		<!-- Hibernate 5.2.6 Final -->

		<!-- MySql Driver -->

	<!-- Maven Compiler Plugin -->


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
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"


		<!-- 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" />

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.

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;

@Table( name = "EMPLOYEES" )
public class Employee {
	private static final long serialVersionUID = 1L;
	@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

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()
			Metadata metadata = new MetadataSources(standardRegistry).addAnnotatedClass(Employee.class)
			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.


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]);

The created project structure will be as given below.

Hibernate Example With Annotations

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

Hibernate Example With Annotations

Please refer to the Github repository here Hibernate-BasicExample-App-With-Annotations

Leave A Reply