Hibernate Tutorials : Hello world example in hibernate

Hello world hibernate example

Hello world example in Hibernate

In this tutorial, I will explain every step to run hello world example in Hibernate framework. Before we start, it is important to setup the environment and create a new Maven project.

Please follow this Configure Maven and Project tutorial to setup environment and create new maven project.

After you setup your environment and created a new maven project. Follow these steps.

Create Database and Table as below :
Database : hibernatetestdb

Table structure

Name Primary Key Data type Auto Increment Allow Null
Id Yes Int Yes No
Name No Varchar(200) No Yes

Directory Strucutre

Hello world hibernate example
Hello world hibernate example

Step 1 : Create Hibernate Configuration file

The core of the Hibernate is it’s configuration file. Hibernate reads database configuration parameters and it’s related mapping files from configuration. So we will create hibernate configuration file and will discuss it’s related terms. hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
 <!-- Database connection settings -->
 <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="connection.url">jdbc:mysql://localhost:3306/hibernatetestdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">admin</property>
 <property name="show_sql">true</property>

 <mapping class="com.hibernatetest.entities.User" />

 </session-factory>
</hibernate-configuration>
<hibernate-configuration/> : Configuration element, Hibernate creates configuration instance which is then used by SessionFactory to provide Session Objects to the application. You can provide configuration details inside this element.

<session-factory/> :  Factory for Session objects in Hibernate application. Inside this element, you can provide database connection details like Driver, URL, username and password etc.

Different Properties

connection.driver_class : Since, we are using JDBC for connecting with the database. We will provide JDBC driver class name.
connection.url : URL of the connection, jdbc:mysql://HOST_NAME_OR_IP:PORT/DB_NAME.
username : user name of the database.
password : Database password.
show_sql : You can enable or disable the query logs.

Step 2 : Create Entity

Create an entity class, Entity class is simple POJO class annotated with Hibernate annotation. This entity is then mapped to the table of relational database by Hibernate later.

User.java
package com.hibernatetest.entities;

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="USER")
public class User {

 @Id
 @Column(name="id")
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private int id;
 
 @Column(name="name")
 private String name;

 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; }
}
@Entity : Annotation which indicates that particular class is entity class. Hibernate then scans all the entity classes to map to relational database. So we need to tell Hibernate which are the entities classes.

@Table : Annotation allows you to specify the name of the table that will be used to persist the entity in database. Annotation uses name attribute to specify the name of the table. You can also override the name of the table, it’s schema and specify unique constraints on columns of table.

@Id : This annotation indicates that the particular field is the primary key of the entity class.

@GeneratedValue : This annotation is the way of specifying the auto increment of a specified column in entity class. This tells, how primary keys should be generated in database. Like in our case Identity.

@Column : This annotation allows you to specify column properties of a table. You can specify different attributes like column name, length, null allowed or not etc.

Step 3 : Create Main Class

We will create a Main class to run the example. We will discuss different terms.  
package com.hibernatetest.main;

import java.util.List;
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.hibernatetest.entities.User;
public class Main {
 public static void main(String[] args) {
 Main.runWithMethodOne();
 }
 @SuppressWarnings({
 "deprecation",
 "unchecked"
 }) public static void runWithMethodOne() {
 Configuration config = new Configuration();
 config.configure("hibernate.cfg.xml");
 SessionFactory factory = config.buildSessionFactory();
 Session session = factory.openSession();
 List < User > users = (List < User > ) session.createQuery("from User").list();
 for (User user: users) {
 System.out.println("User name : " + user.getName());
 }
 }
 @SuppressWarnings("unchecked") public static void runWithMethodTwo() {
 Configuration config = new Configuration();
 config.configure("hibernate.cfg.xml");
 StandardServiceRegistryBuilder regBuilder = new StandardServiceRegistryBuilder();
 regBuilder.applySettings(config.getProperties());
 ServiceRegistry serviceReg = regBuilder.build();
 SessionFactory factory = config.buildSessionFactory(serviceReg);
 Session session = factory.openSession();
 List < User > users = (List < User > ) session.createQuery("from User").list();
 for (User user: users) {
 System.out.println("User name : " + user.getName());
 }
 }
}
We have different methods to configure Hibernate to run this example. We will discuss each method.

runWithMethodOne The org.hibernate.cfg.Configuration is used to build an immutable SessionFactory. You can obtain Configuration object instance by instantiating it directory and provide the configuration files to configure() method.
Configuration config = new Configuration();
 config.configure("hibernate.cfg.xml");
After that, Configuration instance can build session factory by using buildSessionFactory() method of Configuration class.
SessionFactory factory = config.buildSessionFactory();
SessionFactory is now ready to provide Session objects by simply calling openSession() method of SessionFactory. Which will start a new session between application and database server.
Session session = factory.openSession();
Now we can perform transaction with the session object like query, update and delete.
List<User> users = (List<User>) session.createQuery("from User").list();

 for (User user : users) {
 System.out.println("User name : " + user.getName());
 }
createQuery() method takes HQL as input and provides you the list of objects from database.

runWithMethodTwo() To use this method to create SessionFactory, you need Hibernate Core version 4.3.5.Final and above. Create Configuration instance same as above.
Configuration config = new Configuration();
 config.configure("hibernate.cfg.xml");
The org.hibernate.boot.registry.StandardServiceRegistryBuilder is the builder for ServiceRegistry. Use applySettings() method which takes properties from the configuration instance of hibernate. After that, you can create session factory.
StandardServiceRegistryBuilder regBuilder = new StandardServiceRegistryBuilder();
 regBuilder.applySettings(config.getProperties());
After that, you can build ServiceRegistry from the StandardServiceRegistryBuilder which will be able to build SessionFactory.
ServiceRegistry serviceReg = regBuilder.build();
Now, Configuration instance can build session factory by using buildSessionFactory(), but you need to provide ServiceRegistry object to the method. Rest of the code is same as method one.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *