Hibernate Practicals
Hibernate Practicals
Practical # 1
Setting up Maven Project and add Hibernate Dependencies
using Eclipse or STS
● Maven 3.5.3
● JavaSE 1.8
● Hibernate 5.3.7.Final
● IDE - Spring Tool Suite (STS) 3.9.8 /Eclipse
● MySQL - 8.0.13
Development Steps
Step-2
Click on Checkbox for both
● Create a simple project
● Use default Workspace location
Step-3
Provide GroupId and ArtifactId on the next screen.
● GroupId: com.faith.demo
● Artifact Id: EMSv2020-HB
● Name: HibernateDemonstration
Leave other things as they are and click Finish. And you are all set. In the Project
Explorer view, you see the project gets created with the following structure:
3. Configure Hibernate Dependencies to pom.xml
<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>com.faith.demo</groupId>
<artifactId>EMSv2020-HB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>EMSv2020-HB</name>
<description>Employee Management System v2020</description>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.3.7.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
</dependencies>
</project>
You see, here we add dependencies for the project: hibernate-core, hibernate-
annotations, hibernate-entitymanager and mysql-connector-java. Maven
automatically downloads the required JAR files which are shown under the Maven
Dependencies node in the project
You see, we just specify the dependency hibernate-core, but Maven can analyze
and download all the dependencies of hibernate-core as well. That’s really
helpful, right?
Practical # 2
Create a domain model class named Employee, XML based
hibernate configuration file and map file for persistent class to
the corresponding table in the database. Setup Maven project
using Eclipse or STS
Next we will create a hibernate configuration file. The configuration file contains
all the information for the database such as connection_url, driver_class,
username, password etc. The hbm2ddl.auto property is used to create the table
in the database automatically.
Under src/main/resources directory, right click and select New -> XML ->XML File
named hibernate.cfg.xml and write the following code in it. In this xml file we will
register the database and specify the entity class.
Hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/hbusersdb</property>
<property name="connection.username">root</property>
<property name="connection.password">faith</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
In the above xml, the <properties> tag under <session-factory> tag defines all the
properties, and <property> tag defines each property such as database
registration, URL specification, username, and password. These are the Hibernate
properties. This file will configure the database.
Employee.hbm.xml
<hibernate-mapping>
<class name="com.faith.demo.entity.Employee"
table="employee">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
Practical # 3
Create the class that retrieves or stores the persistent object to
the corresponding table in the database and test your program
by INSERT a record. Setup Maven project using Eclipse or STS
StoreDataApp.java
package com.faith.demo.app;
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.faith.demo.entity.Employee;
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}
Next Steps as follows:-
Right Click project and Select RunAs → Maven Clean
Right Click project and Select Maven→ Update Project
8. Display Output
Insert
For result, open the MySQL CLI or Workbench and type the following queries.
use hbusersdb
select * from employee
Practical # 4
Modify the domain class Employee with Salary attribute and set
ID with “increment” class. INSERT a few records and DISPLAY
all. Setup Maven project using Eclipse or STS
Employee.java
package com.faith.demo.entity;
public class Employee {
private int id;
private String firstName, lastName;
private int salary;
public Employee() {
}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
6. Modify the mapping file for Persistent class
Employee.hbm.xml
<hibernate-mapping>
<class name="com.faith.demo.entity.Employee"
table="employee">
<id name="id" type="int" column="id">
<generator class="increment"></generator>
</id>
<property name="firstName" column="firstName" type="string" />
<property name="lastName" column="lastName" type="string" />
<property name="salary" column="salary" type="int" />
</class>
</hibernate-mapping>
Let's create CRUD Operations against a database. In the above shown package
hierarchy, create a package named ‘com.faith.demo.app’, under ‘src/main/java’
(source) package. Create a CRUDManageEmployee.java with addEmployee and
listEmployees methods as follows:
CRUDManageEmployee.java
package com.faith.demo.app;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
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.faith.demo.entity.Employee;
try {
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
System.out.println("successfully inserted");
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return employeeID;
}
try {
tx = session.beginTransaction();
List employees = session.createQuery("FROM
Employee").list();
for (Iterator iterator = employees.iterator();
iterator.hasNext();) {
Employee employee = (Employee) iterator.next();
System.out.print("Employee ID: " +
employee.getId());
System.out.print(" First Name: " +
employee.getFirstName());
System.out.print(" Last Name: " +
employee.getLastName());
System.out.println(" Salary: " +
employee.getSalary());
}
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
Project directory structure is as shown below:-
StoreDataApp.java
package com.faith.demo.app;
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.faith.demo.entity.Employee;
}
}
8. Display Output
List Employees
Practical # 5
Use Hibernate API to perform UPDATE operations against the
database. Using MySQL database.
CRUDManageEmployee.java
package com.faith.demo.app;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
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.faith.demo.entity.Employee;
try {
tx = session.beginTransaction();
Employee employee = (Employee)
session.get(Employee.class, EmployeeID);
employee.setSalary(salary);
session.update(employee);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
}
StoreDataApp.java
package com.faith.demo.app;
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.faith.demo.entity.Employee;
public class StoreDataApp {
public static void main(String[] args) {
CrudManageEmployee crudME = new CrudManageEmployee();
/* Update employee's records */
crudME.updateEmployee(4, 77000);
/* List down all the employees */
crudME.listEmployees();
}
}
Next Steps as follows:-
Right Click project and Select RunAs → Maven Clean
Right Click project and Select Maven→ Update Project
Right Click -->StoreDataApp.java→RunAs→Java Application
CRUDManageEmployee.java
package com.faith.demo.app;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
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.faith.demo.entity.Employee;
try {
tx = session.beginTransaction();
Employee employee = (Employee)
session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
}
StoreDataApp.java
package com.faith.demo.app;
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.faith.demo.entity.Employee;
public class StoreDataApp {
public static void main(String[] args) {
CrudManageEmployee crudME = new CrudManageEmployee();
/* Delete an employee from the database */
crudME.deleteEmployee(4);
}
}
Next Steps as follows:-
Right Click project and Select RunAs → Maven Clean
Right Click project and Select Maven→ Update Project
Right Click -->StoreDataApp.java→RunAs→Java Application
Practical # 7 :
Finding a domain model solution on the following database
diagram by using Hibernate API
Hint: O/R Mappings -> Association : One-to-Many mappings
public Employee() {
}
Now, let us define another POJO class corresponding to CERTIFICATE table so that
certificate objects can be stored and retrieved into the CERTIFICATE table. This
class should also implement both the equals() and hashCode() methods so that
Java can determine whether any two elements/objects are identical.
Certificate.java
package com.faith.demo.entity;
public Certificate() {
}
public Certificate(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
To create the mapping file, Under src/main/resources directory, right click and
select New -> XML ->XML File named employee.hbm.xml and write the following
code in it. It must be outside the package.
Employee.hbm.xml
package com.faith.demo.entity;
<?xml version='1.0' encoding='UTF-8'?>
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.faith.demo.entity.Employee" table="EMPLOYEE">
<id name="id" type="int" column="id">
<generator class="increment" />
</id>
<set name="certificates" cascade="all">
<key column="employee_id" />
<one-to-many class="com.faith.demo.entity.Certificate" />
</set>
<class name="com.faith.demo.entity.Certificate"
table="CERTIFICATE">
<meta attribute="class-description">
This class contains the certificate records.
</meta>
Notes:
● The <generator> element within the id element is used to generate the
primary key values automatically. The class attribute of the generator
element is set to native to let hibernate pick up either identity, sequence
or hilo algorithm to create primary key depending upon the capabilities of
the underlying database.
● The <set> element sets the relationship between Certificate and Employee
classes. We used the cascade attribute in the <set> element to tell
Hibernate to persist the Certificate objects at the same time as the
Employee objects. The name attribute is set to the defined Set variable in
the parent class, in our case it is certificates. For each set variable, we need
to define a separate set element in the mapping file.
● The <key> element is the column in the CERTIFICATE table that holds the
foreign key to the parent object i.e. table EMPLOYEE.
Let's create CRUD Operations against a database. In the above shown package
hierarchy, create a package named ‘com.faith.demo.app’, under ‘src/main/java’
(source) package. Create a CRUDManageEmployee.java with addEmployee,
listEmployees, updateEmployee and deleteEmployee methods as follows:
CRUDManageEmployee.java
package com.faith.demo.app;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.HibernateException;
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.faith.demo.entity.Certificate;
import com.faith.demo.entity.Employee;
try {
tx = session.beginTransaction();
Employee employee = new Employee(fname,
lname, salary);
employee.setCertificates(cert);
employeeID = (Integer) session.save(employee);
tx.commit();
System.out.println("successfully inserted");
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return employeeID;
}
try {
tx = session.beginTransaction();
List employees = session.createQuery
("FROM Employee").list();
for (Iterator iteratorOne = employees.iterator();
iteratorOne.hasNext();
){
Employee employee =
(Employee) iteratorOne.next();
System.out.print("Employee ID: " +
employee.getId());
System.out.print(" First Name: " +
employee.getFirstName());
System.out.print(" Last Name: " +
employee.getLastName());
System.out.println(" Salary: " +
employee.getSalary());
Set certificates =
employee.getCertificates();
for (Iterator iteratorTwo = certificates.iterator();
iteratorTwo.hasNext();
){
Certificate certName = (Certificate) iteratorTwo.next();
System.out.println("Certificate: " +
certName.getName());
}
}
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
try {
tx = session.beginTransaction();
Employee employee = (Employee)
session.get(Employee.class, EmployeeID);
employee.setSalary(salary);
session.update(employee);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
try {
tx = session.beginTransaction();
Employee employee = (Employee)
session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
8. Create an Application class
Let’s create a main class StoreDataApp.java, under src/main/java’ (source)
com.faith.demo.app’ as follows:-
StoreDataApp.java
package com.faith.demo.app;
import java.util.HashSet;
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 org.hibernate.cfg.Configuration;
import com.faith.demo.entity.Certificate;
import com.faith.demo.entity.Employee;
List
MySQL Output
Update
Delete