JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Basic Hibernate CRUD operations example.


In this example we are giving examples on all basic CRUD operations on database using Hibernate.

Create DB Table


CREATE TABLE EMPLOYEES (

	EMP_ID BIGINT NOT NULL AUTO_INCREMENT,
	NAME VARCHAR(252),
	DEPARTMENT VARCHAR(128),
	SALARY BIGINT,
	JOINED_ON TIMESTAMP,
	PRIMARY KEY (EMP_ID)
);

INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (1, 'Nataraja G', 'Documentation', 10000, CURRENT_TIMESTAMP);
INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (2, 'Amar M', 'Entertainment', 12000, CURRENT_TIMESTAMP);
INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (3, 'Nagesh Y', 'Admin', 25000, CURRENT_TIMESTAMP);
INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (4, 'Vasu V', 'Security', 2500, CURRENT_TIMESTAMP);
                    

Maven pom.xml reference

Here is the reference for the pom.xml will all required dependencies:

<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.java2novice</groupId>
	<artifactId>hibernate-examples</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>hibernate-examples</name>

	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<dependencies>
		<!-- Hibernate core dependency -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.0.0.Final</version>
		</dependency>
		<!-- MySQL database driver -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.37</version>
		</dependency>
	</dependencies>
</project>

Hibernate Configuration File

Create hibernate xml based configuration file in your resources folder (classpath). This file includes hibernate configurations like driver class, DB connectivity URL, DB credentials and so on...

j2n-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>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/java2novice</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<property name="show_sql">false</property>
	</session-factory>
</hibernate-configuration>

Hibernate Mapping with Entity Class

Here is the class Employee which maps to EMPLOYEES table in database.

The table columns are mapped to class member variables. Use @Column annotation to map DB columns with class variables.

package com.java2novice.model;

import java.io.Serializable;
import java.util.Date;

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 implements Serializable {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="EMP_ID")
	private Long empId;

	private String name;

	private String department;

	private Long salary;

	@Column(name="JOINED_ON")
	private Date joinedOn;

	public Long getEmpId() {
		return empId;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public Long getSalary() {
		return salary;
	}

	public void setSalary(Long salary) {
		this.salary = salary;
	}

	public Date getJoinedOn() {
		return joinedOn;
	}

	public void setJoinedOn(Date joinedOn) {
		this.joinedOn = joinedOn;
	}

	@Override
	public String toString() {

		return this.empId+" | "+this.name+" | "+this.department+" | "+this.salary+" | "+this.joinedOn;
	}
}

Hibernate Utility Class

This class manages hibernate session.

package com.java2novice.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.java2novice.model.Employee;

public class HibernateUtil {

	private static SessionFactory sessionFactory = null;

	static {
		try{
			loadSessionFactory();
		}catch(Exception e){
			System.err.println("Exception while initializing hibernate util.. ");
			e.printStackTrace();
		}
	}

	public static void loadSessionFactory(){

		Configuration configuration = new Configuration();
		configuration.configure("/j2n-hibernate.cfg.xml");
		configuration.addAnnotatedClass(Employee.class);
		ServiceRegistry srvcReg = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
		sessionFactory = configuration.buildSessionFactory(srvcReg);
	}

	public static Session getSession() throws HibernateException {

		Session retSession=null;
	    	try {
	    		retSession=sessionFactory.openSession();
	    	}catch(Throwable t){
			System.err.println("Exception while getting session.. ");
			t.printStackTrace();
	    	}
	    	if(retSession == null) {
	    		System.err.println("session is discovered null");
	    	}

	    	return retSession;
    }
}

Hibernate Dao Class

This class gives examples on reading all record, reading a record based on primary key, deleting record, etc.

package com.java2novice.hibernate;

import java.util.Date;
import java.util.List;

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

import com.java2novice.model.Employee;

public class EmployeesDao {

	public List<Employee> getEmployeeList(){

		Session session = null;
		List<Employee> empList = null;
		try {
			session = HibernateUtil.getSession();
			String queryStr = "select emp from Employee emp";
			Query query = session.createQuery(queryStr);
			empList = query.list();
		} catch(Exception ex) {
			ex.printStackTrace();
			// handle exception here
		} finally {
			try {if(session != null) session.close();} catch(Exception ex) {}
		}
		return empList;
	}

	public Employee getEmployeeById(Long empId){

		Session session = null;
		Employee emp = null;
		try {
			session = HibernateUtil.getSession();
			String queryStr = "select emp from Employee emp";
			emp = session.get(Employee.class, empId);

		} catch(Exception ex) {
			ex.printStackTrace();
			// handle exception here
		} finally {
			try {if(session != null) session.close();} catch(Exception ex) {}
		}
		return emp;
	}

	public void insertEmployee(Employee emp) {

		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtil.getSession();
			transaction = session.beginTransaction();
			session.save(emp);
			System.out.println("inserted employee: "+emp.getName());
			transaction.commit();
		} catch(Exception ex) {
			ex.printStackTrace();
			// handle exception here
			if(transaction != null) transaction.rollback();
		} finally {
			try {if(session != null) session.close();} catch(Exception ex) {}
		}
	}

	public void deleteEmployee(Employee emp) {

		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtil.getSession();
			transaction = session.beginTransaction();
			session.delete(emp);
			transaction.commit();
			System.out.println("deleted employee: "+emp.getName());
		} catch(Exception ex) {
			ex.printStackTrace();
			// handle exception here
			if(transaction != null) transaction.rollback();
		} finally {
			try {if(session != null) session.close();} catch(Exception ex) {}
		}
	}

	public static void main(String a[]) {

		EmployeesDao empDao = new EmployeesDao();

		Employee emp = new Employee();
		emp.setName("Babu");
		emp.setDepartment("Security");
		emp.setJoinedOn(new Date());
		emp.setSalary(new Long(5250));
		empDao.insertEmployee(emp);

		System.out.println("---------------------------");

		List<Employee> empList = empDao.getEmployeeList();
		System.out.println("emp size: "+empList.size());
		empList.stream().forEach(System.out::println);

		System.out.println("---------------------------");

		Employee empObj = empDao.getEmployeeById(emp.getEmpId());
		System.out.println(empObj);

		System.out.println("---------------------------");
		empDao.deleteEmployee(empObj);

		System.out.println("---------------------------");

		empList = empDao.getEmployeeList();
		System.out.println("emp size: "+empList.size());
		empList.stream().forEach(System.out::println);

		System.out.println("---------------------------");
	}
}

Output:
inserted employee: Babu
---------------------------

emp size: 5
1 | Nataraja G | Documentation | 10000 | 2017-12-16 11:59:59.0
2 | Amar M | Entertainment | 12000 | 2017-12-16 11:59:59.0
3 | Nagesh Y | Admin | 25000 | 2017-12-16 11:59:59.0
4 | Vasu V | Security | 2500 | 2017-12-16 12:00:21.0
9 | Babu | Security | 5250 | 2017-12-18 15:31:57.0
---------------------------
9 | Babu | Security | 5250 | 2017-12-18 15:31:57.0
---------------------------
deleted employee: Babu
---------------------------
emp size: 4
1 | Nataraja G | Documentation | 10000 | 2017-12-16 11:59:59.0
2 | Amar M | Entertainment | 12000 | 2017-12-16 11:59:59.0
3 | Nagesh Y | Admin | 25000 | 2017-12-16 11:59:59.0
4 | Vasu V | Security | 2500 | 2017-12-16 12:00:21.0
---------------------------
<< Previous Program | Next Program >>

Hibernate Examples

  1. Hibernate hello world (initial setup) example.
  2. What is hibernate.cfg.xml configuration?
  3. What are the basic hibernate persistent annotations?
  4. What is SessionFactory in Hibernate?
  5. What is Session object in Hibernate?
  6. List Hibernate Session interface methods.
  7. What is Hibernate Query object?
  8. Basic Hibernate CRUD operations example.
  9. Hibernate Bidirectional One-to-One mapping using @OneToOne annotation.
  10. Hibernate Unidirectional One-to-One mapping using @OneToOne annotation.
  11. Hibernate Eager vs Lazy Fetch Type
  12. Hibernate Unidirectional One-to-Many mapping using @OneToMany annotation.
  13. Hibernate Bidirectional One-to-Many mapping using @OneToMany annotation.
  14. Hibernate Many-to-Many mapping example using @ManyToMany annotation.
  15. How to enable logging (log4j) in Hibernate?
Knowledge Centre
ServletOuptputStream Vs PrintWriter
ServletOutputStream: ServletResponse.getOutputStream() returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data, it sends the raw data as it is.

PrintWriter: ServletResponse.getWriter() returns PrintWriter object which sends character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified then it does default character encoding.
Famous Quotations
Before you go and criticize the younger generation, just remember who raised them.
-- Unknown Author

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.