Create Basic Hibernate Program

Getting Started with Hibernate

Table of Contents

Hibernate is an ORM framework that helps in accessing database tables from Java code. It is an object-oriented way of accessing database tables and it eliminates boilerplate code that is required with JDBC.

In this article, I will be explaining how you can create a basic Hibernate application that saves a record into a database table via Hibernate.

Prerequisites

Before writing code, you need to ensure that you have installed and configured the database that you will be connecting to from your Hibernate code. I will be using a MySQL database. You also need to ensure that you have the database driver JAR files as well as Hibernate JAR files. If you are using a MySQL database and Maven as the dependency management tool, you can add the following dependencies:

  <dependencies>
  	<dependency>
  		<groupId>org.hibernate</groupId>
  		<artifactId>hibernate-core</artifactId>
  		<version>5.3.4.Final</version>
  	</dependency>
  	<dependency>
  		<groupId>mysql</groupId>
  		<artifactId>mysql-connector-java</artifactId>
  		<version>8.0.12</version>
  	</dependency>
  </dependencies>

Creating a database table

Once the database is configured, you will need to create a database table which you will access via Hibernate. I will be using a table called STUDENT. You can create this table by running the following SQL:

create table STUDENT (
   id INT NOT NULL auto_increment,
   full_name VARCHAR(50),
   marks     DOUBLE ,
   PRIMARY KEY (id)
);

So, this is a Student table that capture student information. It has columns corresponding to the name of the Student and the marks obtained by the student. It also has an id column which is the primary key column.

Creating POJO class

Hibernate requires you to create a simple POJO class that has fields corresponding to the columns in the database table. The following code demonstrates a Student class corresponding to the Student table:

@Entity
@Table(name = "Student")
public class Student {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	int id;
	
@Column(name="full_name")
String name;
	
	double marks;
}

The Student class has some Hibernate annotations which tell Hibernate how to map this class to the database table. These are as follows:

  • @Entity – This annotation specifies that this is an entity class and that it maps to a database table.
  • @Table – This is an optional annotation that can be specified on the class. It indicates the name of the database table that the entity maps to. If not specified, it defaults to the entity name.
  • @Id – This is a field-level annotation.  It indicates that the field that maps to the primary key column in the database. 
  • @GeneratedValue – This annotation is used on the field with the @Id annotation and specifies how the primary key values will be generated. Hibernate supports many primary key generation strategies. Here, the GenerationType.IDENTITY is used which means that the primary key column is an auto incremented column in the database
  • @Column – This is an optional field-level annotation. It is used to specify the name and other details of the column to which the field is mapped.  If not specified, it defaults to the field name.

Create hibernate configuration file

Hibernate requires you to provide a configuration file that contains all the database related information like the database username, password etc. Hibernate uses this information to connect to the database.  

The following is a basic Hibernate configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> 
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">URL</property>
		<property name="hibernate.connection.username">username</property>
		<property name="hibernate.connection.password">password</property>
		<mapping class="demo.Student" />
	</session-factory>
</hibernate-configuration>

  • Hibernate.dialect – This specifies the underlying database that hibernate should connect to. Hibernate uses this to generate database specific SQL statements. Since I’m using a MySQL database, I’ve specified MySQLDialect.
  • hibernate.connection.driver_class – This specifies the JDBC driver class to be used. I’ve specified the MySQL JDBC driver.
  • hibernate.connection.url – This specifies the database connection URL
  • hibernate.connection.username – This specifies the database connection username
  • hibernate.connection.password – This specifies the database connection password
  • mapping-class – This specifies the name of the class that needs to be mapped to the database.

In addition, there are other several other properties that can be specified in the configuration file.

Writing and executing code

After creating the POJO class and the Hibernate configuration file, the next step is to write the code that connects to the database as shown below:

public class Main {
	public static void main(String args[]) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		Student student = new Student("John Doe",87.5);
		session.save(student);
		tx.commit();
		session.close();
		sessionFactory.close();
	}

} 

This code creates a new Student object and saves it to the database. Let us take a closer look at the main parts of this code:

  • A SessionFactory object is first created. The SessionFactory contains all the data in the hibernate configuration file. It is usually created only once at the start of the application and kept for later use.
  • A Session object is then created from the SessionFactory. A Session represents a physical connection with the database. The session object is used to actually save data and retrieve data from the database.
  • Next a Student object is created and the session.save method is invoked. This method call translates into an insert query and inserts a record corresponding to a Student into the Student database table

When this code is executed, a database record will be inserted into the Student table.

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

RELATED POSTS

Java Tutorial #2 – Operators in Java

Table of Contents Introduction 1. Assignment Operator 2. Arithmetic Operators 3. Compound Operators 4. Increment & Decrement Operators 5. Relational Operators 6. Logical Operators Introduction Operators are an essential...

Convert List to Array Using Stream with Param

There is an overloaded version of the Stream.toArray method which can be used to return a result array that is of the same data...

Concatenate Strings Using Plus Operator

In Java, a String is a sequence of characters. There are often programming situations where you will need to concatenate Strings. There are several...

Â

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

SIMILAR ON CODEX

FEATURED PROJECTS

Windows JDK Manager (win-jdk-Manager)

ADjo LABS PROJECT : Simple and lightweight desktop utility with Interactive cmd Interface for easy view, re-point and switching between JAVA versions on windows. Demonstrating the capability...

MORE IN THIS CATEGORY

Java Tutorial #6 – Jump Statements

Introduction The break statement is used to stop further execution. It can be used either in a loop or within a switch statement. Break Statement The break...

Setting Max/Min Digits For Decimal Numbers With Java DecimalFormat

The DecimalFormat class offers the following four such methods which can be used to easily set the maximum and/or minimum digits for decimal numbers....

Maven CLI Options and Switches Reference

Maven offers a good set of commands and CLI Options to carry out wide range of Dev tasks. Most of these commands are in...

CHECKOUT TUTORIALS

Getting Started with Selenium WebDriver

Table of Contents 1. Selenium and Selenium Web Driver 2. Setting-Up the Environment 3. Test Script with Selenium Web Driver 3.1) Creating a project 3.2) Creating...
- Advertisement -spot_img