How To Create the Demo Hibernate Application
To create the hibernate application, follow the following steps:-
- Create the Persistent class
- Create the mapping file for Persistent class
- Create the Configuration file
- Create the class that insert the persistent object into DB
- Load the jar file
Create the Persistent class
In this step, you should create simple POJO class, who can map with database easily. Since, hibernate works on the concept of ORM.
package com.programmingshifts.classes;
public class Student {
int studentId;
String fName, Lname;
//generate setter & getter
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getLname() {
return Lname;
}
public void setLname(String lname) {
Lname = lname;
}
//generate constructor
public Student() {
super();
}
}
In the above class, you have noticed that there may be some basic rule to create the class.
There is a concept that developers should follow the concept.
1. Create no-argument constructor: create public visibility so that hibernate can create an instance of this class by newInstance() method.
2. Create an identifier property: assign an attribute as id, so that it can work similar to primary key in table.
3. Create setter & getter methods of each attribute of class: Hibernate can understand the method easily.
4. Non-final class: keep in mind that hibernate uses the concept of proxies that depends on this persistent class. Programmers cannot use proxies for lazy association fetching.
Create the mapping file for Persistent class
For better learning, first go through myStudent.hbm.xml file as below:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.programmingshifts.classes.Student" table="Student2018">
<id name="studentId">
<generator class="assigned"></generator>
</id>
<property name="fName"></property>
<property name="Lname"></property>
</class>
</hibernate-mapping>
As, you can see the above code tells you that this file myStudent.hbm.xml contains main tag as hibernate-mapping and this tags contains all classes tags. In this example, we have created Student class as persistent java files. If you need more than one class files then you can map accordingly or you can create separate file for mapping.
Create the Configuration file:
In our, example we have created Hibernet.cfg.xml file, code is as below:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernetdemo</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="myStudent.hbm.xml"/>
</session-factory>
</hibernate-configuration>
This file contains database level credentials, driver and other properties.
Create the class that insert the persistent object into DB
As you can see the below code, we have created simple java file in which there is a main that runs the java standalone file.
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import com.programmingshifts.classes.Student;
public class SaveStudentData_Main {
public static void main(String[] args) {
//Create typesafe ServiceRegistry object
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("Hibernet.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
Student sobj=new Student();
sobj.setStudentId(100);
sobj.setfName("Navi");
sobj.setLname("Singh");
session.save(sobj);
t.commit();
System.out.println("****Data Inserted into DB****done");
factory.close();
session.close();
}
}
In the above code, we followed some basic concept about object like.
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder();
ssr.configure("Hibernet.cfg.xml").build();
Then, we have created the object of metadata like.
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
In the below code we have created sessionfactory class object that will create session object and this session object will create transaction object.
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
Further you can create the object that should have some data, we will save the data by using save method and further commit this data.
Finally, you can see the data in database tables(remember one thing: you should create database & tables before program to run).
You can see the MYSQL steps as below:
Enter password: ****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 89
Server version: 5.7.18-log MySQL Community Server (GPL)
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database hibernetdemo;
Query OK, 1 row affected (0.02 sec)
mysql> use hibernetdemo;
Database changed
mysql> create table student2018(id int, fname varchar(20), lname varchar(20));
Query OK, 0 rows affected (0.40 sec)
mysql> drop table student2018;
Query OK, 0 rows affected (0.18 sec)
mysql> create table student2018(studentid int, fname varchar(20), lname varchar(20));
Query OK, 0 rows affected (0.32 sec)
mysql> select * from student2018;
+-----------+-------+-------+
| studentid | fname | lname |
+-----------+-------+-------+
| 100 | Navi | Singh |
+-----------+-------+-------+
1 row in set (0.00 sec)
mysql>