Site icon Automation Dojos

Create Basic Hibernate Program

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.

Exit mobile version