JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Hibernate hello world (initial setup) example.


In this example we are giving steps to configure Hibernate and get records from MySql database using Hibernate session. We are using Hibernate 5.0.0Final version.

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

DB Employees Table Records:
mysql> select * from employees;
+--------+------------+---------------+--------+---------------------+
| EMP_ID | NAME       | DEPARTMENT    | SALARY | JOINED_ON           |
+--------+------------+---------------+--------+---------------------+
|      1 | Nataraja G | Documentation |  10000 | 2017-12-16 11:59:59 |
|      2 | Amar M     | Entertainment |  12000 | 2017-12-16 11:59:59 |
|      3 | Nagesh Y   | Admin         |  25000 | 2017-12-16 11:59:59 |
|      4 | Vasu V     | Security      |   2500 | 2017-12-16 12:00:21 |
+--------+------------+---------------+--------+---------------------+
4 rows in set (0.00 sec)

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 vairables. Use @Column annotation to map DB columns with class variables.

package com.java2novice.model;

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.AUTO)
	@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 makes a request to database using hibernate and reads data.

package com.java2novice.hibernate;

import java.util.List;

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

import com.java2novice.model.Employee;

public class EmployeesDao {

	public List<Employee> getEmployeeList(){

		Session session = null;
		session = HibernateUtil.getSession();
		String queryStr = "select emp from Employee emp";
		Query query = session.createQuery(queryStr);

		return query.list();
	}

	public static void main(String a[]) {

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

Output:
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
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
What is daemon thread?
Daemon thread is a low priority thread. It runs intermittently in the back ground, and takes care of the garbage collection operation for the java runtime system. By calling setDaemon() method is used to create a daemon thread.
Famous Quotations
Good judgment comes from experience, and experience comes from bad judgment.
-- Barry LePatner

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 © 2018 by Nataraja Gootooru. All Rights Reserved.