Basic Implementation of Hibernate

A small example on how to use Hibernate in a project
Earlier we looked at what Hibernate is and what the need for it is.

Now that we know how Hibernate makes programming so much easier, let us look into how to program with Hibernate in the most basic sense possible.

This tutorial will follow easy steps to understand the functionality of Hibernate.

Prerequisites

  1. IntelliJ Idea IDE
  2. MySQL database (Version 8 or above)

Creating a Hibernate Program

1. Create a new Maven project.
File -> New -> Project -> Maven -> Maven Quickstart Archetype -> Next


Name the file and click Finish.

2. Configure the pom.xml file in the following manner.

<?xml version="1.0" encoding="UTF-8"?>

<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>org.example</groupId>
<artifactId>TestHibernate</artifactId>
<version>1.0-SNAPSHOT</version>

<name>TestHibernate</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.18.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
</dependencies>

<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

3. Create a new class called Student as follows.

package org.example;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student_table")
public class Student {
@Id
private int id;
private String name;
private int age;


public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

4. In the Resources directory, create a configuration file named hibernate.cfg.xml and enter the following attributes.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/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/testHibernate</property>
<property name="hibernate.connection.autocommit">false</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect"> org.hibernate.dialect.MySQL8Dialect </property>
<!-- <property name="hibernate.connection.CharSet" value="utf8"/>-->
<!-- <property name="hibernate.connection.characterEncoding" value="utf8"/>-->
<!-- <property name="hibernate.connection.useUnicode" value="true"/>-->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
The values defined in the property pertain to the database that has been created in your MySQL.

Note: If the SQL version you have is not 8, in the hibernate.dialect, change the value to MySQLDialect or MySQL5Dialect (if your version of SQL is 5).

5. In the App class (which is auto-generated in the Maven project) write the following codes.

package org.example;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class App
{
public static void main( String[] args )
{
Student studentA = new Student();
studentA.setId(100);
studentA.setName("Bob");
studentA.setAge(16);

Configuration con = new Configuration().configure().addAnnotatedClass(Student.class);

SessionFactory sf = con.buildSessionFactory();

Session session = sf.openSession();

Transaction transaction = session.beginTransaction();

session.save(studentA);

transaction.commit();
}
}

6. The organization of the folders should be as follows;



7. Now, run the App.class. 

8. In the database, if you run the query to view the Student Table, the record will be inserted.



To recap, we didn't write a single database query within the Java coding. It was fully generated with the help of Hibernate.

Hibernate is smart enough to generate all the necessary queries in order to create the table and thereafter, insert values from the object into that table.

This is one of the most simple implementations of Hibernate, but it shows just how useful it could be.

Happy Hibernating! (With Java, of course)




Comments

Popular Posts