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

Format Decimal Numbers using Strings Within Pattern

As mentioned in earlier posts, the java.text.DecimalFormat class is used to format decimal numbers via predefined patterns specified as String. Apart from the decimal separator,...

Java Tutorial #5 – Loop Statements

Iteration statements are used to repeat a particular block of code until a certain condition is true. In this article, we will be taking...

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

Â

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

SEPA Bulk File Generator and Validator

ADjo LABS PROJECT: SEPA Bulk File Generator and Validator. Supported File Types PAIN008, PAIN001, PACS003 and PACS008. Tested for supporting PAIN.008.001.001 and PAIN.008.001.002 (version 1&2). The XML...

MORE IN THIS CATEGORY

How To Remove Duplicates From List in Java

Introduction A List is an interface in the Java collection framework which can be used to store a group of objects. A List is ordered...

Remove Duplicates from List Using For-Loop

The simplest way to remove duplicates from a 'List' is to use a for-loop. The following code snippet demonstrates this method. First, the code creates...

Concatenate Strings Using StringBuilder.append()

In addition to String, Java has the java.lang.StringBuffer and java.lang.StringBuilder classes. These can also be used to concatenate Strings. The advantage of these...

CHECKOUT TUTORIALS

Working with Selenium WebElements

Table of Contents 1. Selenium WebElements 2. WebElement Locators 3. Working With Text Box 4. Working With Buttons 5. Checkboxes and Radio Buttons 6....
- Advertisement -spot_img