0% found this document useful (0 votes)
166 views

Hibernate Practicals

This document provides instructions for setting up a Hibernate project in Eclipse or Spring Tool Suite using Maven. It discusses creating a Maven project, adding Hibernate dependencies to pom.xml, creating an Employee domain class and mapping file, and configuring the hibernate.cfg.xml file. It also provides code samples for a class to store an Employee object in the database and test the insertion.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
166 views

Hibernate Practicals

This document provides instructions for setting up a Hibernate project in Eclipse or Spring Tool Suite using Maven. It discusses creating a Maven project, adding Hibernate dependencies to pom.xml, creating an Employee domain class and mapping file, and configuring the hibernate.cfg.xml file. It also provides code samples for a class to store an Employee object in the database and test the insertion.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Hibernate Practicals-

Practical # 1
Setting up Maven Project and add Hibernate Dependencies
using Eclipse or STS

Notes: Hibernate is a high performance Object/Relational mapping (ORM)


framework completely used in Java. Hibernate also provides query service along
with persistence. This gives developers a way to map the object structures in Java
classes to relational database tables.
ORM framework eases to store the data from object instances into persistence
data stores and load that data back into the same object structure. ORM is
actually a programming technique for converting data between relational
databases and object oriented programming languages.

Some pros of using ORM are the followings:

1. Hides details of SQL queries from object orientation logic


2. Database implementation is sorted out on its own
3. Fast development in application and easy code generation
4. Transaction management and automatic key generation

Hibernate has three different components:


● Entities – Entities are classes mapped by Hibernate to relational
database tables. These are simple Java classes.
● Configuration Metadata – This contains the information about how to
map the entities to relational database tables. Java provides an
XML/Annotation based configuration file. This information is used at
runtime to map the data store and back to Java objects.
● Hibernate Query Language (HQL) – Queries sent to the database in
hibernate can be formulated in Native SQL or Hibenate’s own query
language. These queries are translated at runtime into the currently
used dialect of the chosen product.
Technologies and tools used

● 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

1. Create a Simple Maven Project


2. Project Directory Structure
3. Add jar Dependencies to pom.xml

1. Setup Java Maven Project


Step-1
1. Open Spring Tool Suite 4

2. Click on File -> New -> Maven Project

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

● Description: Employee Management System


2. Project Directory Structure

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

Next, we need to add dependencies in Maven’s Project Object Model (pom.xml)


for Hibernate, JPA and MySQL Connector Java. Open the pom.xml file in XML
mode and insert the following XML just before the </project> tag as highlighted:

<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

Re-use practical # 1 step from 1 to 3

4. Create Hibernate Configuration file

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.

5. Create the Persistent class


In the above shown hierarchy, create a package named ‘com.faith.demo.entity’,
under the ‘src/main/java’ (Source) package. Create a class named Employee.java
under given package as follows
Employee.java
package com.faith.demo.entity;

public class Employee {


private int id;
private String firstName, lastName;

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;
}
}

6. Create the mapping file for Persistent class


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

<?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.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

Re-use practical # 2 step 4 to 6


7. Create the class that retrieves or stores the persistent
object
Now we will create a test program to insert employee data in the database table.
In this class, we are simply storing the employee object to the database. Let’s
Create a main class and run an application.

Create a new class named StoreDataApp.java with main class under


src/main/java’ (source) com.faith.demo.app’ package and type as follows:-

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) {

StandardServiceRegistry ssr = new


StandardServiceRegistryBuilder().
configure("hibernate.cfg.xml").build();
Metadata meta = new
MetadataSources(ssr).
getMetadataBuilder().build();
SessionFactory factory = meta.
getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
Employee e1 = new Employee();
e1.setId(3);
e1.setFirstName("Ganga");
e1.setLastName("Vijay");

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

Right Click -->StoreDataApp.java→RunAs→Java Application

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

Re-use practical # 2 step 4

5. Modify the Persistent class


In the above shown hierarchy, create a package named ‘com.faith.demo.entity’,
under the ‘src/main/java’ (Source) package. Modify the class named
Employee.java under given package as follows

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

To modify the mapping file, Under src/main/resources directory, double click


employee.hbm.xml and write the following code in it. It must be outside the
package.

Employee.hbm.xml

<?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.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>

7. 1- CRUD Operations - INSERT and LIST

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;

public class CrudManageEmployee {

StandardServiceRegistry ssr = new


StandardServiceRegistryBuilder().configure(
"hibernate.cfg.xml").build();
Metadata meta = new
MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory =
meta.getSessionFactoryBuilder().build();

/* Method to CREATE an employee in the database */


public Integer addEmployee(String fname, String lname, int salary) {

Session session = factory.openSession();


Transaction tx = null;
Integer employeeID = null;

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;
}

/* Method to READ all the employees */


public void listEmployees() {
Session session = factory.openSession();
Transaction tx = null;

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:-

8. Modify the class that retrieves or stores the persistent object


Let’s modify the main class StoreDataApp.java, under src/main/java’ (source)
com.faith.demo.app’ as follows:-

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();

/* Add few employee records in database */


Integer empID1 = crudME.addEmployee("Ganga", "Vijay", 55000);

/* 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

8. Display Output

List Employees
Practical # 5
Use Hibernate API to perform UPDATE operations against the
database. Using MySQL database.

Re-use practical # 4 step from 7.1


7.2 - CRUD Operation - UPDATE

7. 2- CRUD Operations - UPDATE


In the above shown package hierarchy, under package named
‘com.faith.demo.app’, Edit CRUDManageEmployee.java by adding a new method
for Updating an Employee.

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;

public class CrudManageEmployee {

StandardServiceRegistry ssr = new


StandardServiceRegistryBuilder().configure(
"hibernate.cfg.xml").build();
Metadata meta = new
MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory =
meta.getSessionFactoryBuilder().build();
/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary) {
Session session = factory.openSession();
Transaction tx = null;

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();
}
}
}
}

Re-use practical # 4 step 8


9. Modify a main class and run an application
Let’s modify the main class StoreDataApp.java, under src/main/java’ (source)
com.faith.demo.app’ as follows:-

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

10. Display Output


Update
Practical # 6
Use Hibernate API to perform DELETE operations against the
database. Using MySQL database.

Re-use practical # 4 step from 7.2


7.3 - CRUD Operation - DELETE

7. 3- CRUD Operations - DELETE


In the above shown package hierarchy, under package named
‘com.faith.demo.app’, Edit CRUDManageEmployee.java by adding a new method
for Deleting an Employee.

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;

public class CrudManageEmployee {

StandardServiceRegistry ssr = new


StandardServiceRegistryBuilder().configure(
"hibernate.cfg.xml").build();
Metadata meta = new
MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory =
meta.getSessionFactoryBuilder().build();
/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID) {
Session session = factory.openSession();
Transaction tx = null;

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();
}
}
}
}

Re-use practical # 4 step 8


9. Modify a main class and run an application
Let’s modify the main class StoreDataApp.java, under src/main/java’ (source)
com.faith.demo.app’ as follows:-

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);

/* 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

10. Display Output


Delete
Multiple Tables CRUD Operations

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

Notes: A One-to-Many mapping can be implemented using a Set java collection


that does not contain any duplicate element. A Set is mapped with a <set>
element in the mapping table and initialized with java.util.HashSet. You can use
Set collection in your class when there is no duplicate element required in the
collection.
Consider a situation where we need to store our employee records in EMPLOYEE
table. Further, assume each employee can have one or more certificates
associated with him/her. So, we will store certificate related information in a
separate table

Re-use practical # 1 step from 1 to 3 and


Re-use practical # 2 step 4
Project Directory Structure

5. Create the Persistent class


Let us implement our POJO class Employee, which will be used to persist the
objects related to EMPLOYEE table and having a collection of certificates in a Set
variable.

In the above shown hierarchy, create a package named ‘com.faith.demo.entity’,


under the ‘src/main/java’ (Source) package. Create a class named Employee.java
and Certificate.java under given package as follows:
Employee.java
package com.faith.demo.entity;

public class Employee {

private int id;


private String firstName;
private String lastName;
private int salary;
private Set certificates;

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 first_name) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String last_name) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public Set getCertificates() {
return certificates;
}
public void setCertificates(Set certificates) {
this.certificates = certificates;
}
}

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 class Certificate {


private int id;
private String name;

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;
}

public void setName(String name) {


this.name = name;
}
public boolean equals(Object obj) {
if (obj == null)
return false;
if (!this.getClass().equals(obj.getClass()))
return false;

Certificate obj2 = (Certificate) obj;


if ((this.id == obj2.getId()) && (this.name.equals(obj2.getName()))) {
return true;
}
return false;
}
public int hashCode() {
int tmp = 0;
tmp = (id + name).hashCode();
return tmp;
}
}
6. Define Hibernate Mapping File
Let us develop our mapping file, which instructs Hibernate how to map the
defined classes to the database tables.

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>

<property name="firstName" column="firstName" type="string" />


<property name="lastName" column="lastName" type="string" />
<property name="salary" column="salary" type="int" />
</class>

<class name="com.faith.demo.entity.Certificate"
table="CERTIFICATE">

<meta attribute="class-description">
This class contains the certificate records.
</meta>

<id name="id" type="int" column="id">


<generator class="increment" />
</id>

<property name="name" column="certificate_name" type="string" />


</class>
</hibernate-mapping>

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 <property> element is used to map a Java class property to a column in


the database table. The name attribute of the element refers to the
property in the class and the column attribute refers to the column in the
database table. The type attribute holds the hibernate mapping type, this
mapping type will convert from Java to SQL data type.

● 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.

● The <one-to-many> element indicates that one Employee object relates to


many Certificate objects
7- CRUD Operations

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;

public class CrudManageEmployee {

StandardServiceRegistry ssr = new


StandardServiceRegistryBuilder().configure
("hibernate.cfg.xml").build();
Metadata meta = new
MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory =
meta.getSessionFactoryBuilder().build();
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname,
int salary, Set cert) {

Session session = factory.openSession();


Transaction tx = null;
Integer employeeID = null;

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;
}

/* Method to READ all the employees */


public void listEmployees() {
Session session = factory.openSession();
Transaction tx = null;

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();
}
}

/* Method to UPDATE salary for an employee */


public void updateEmployee(Integer EmployeeID, int salary) {
Session session = factory.openSession();
Transaction tx = null;

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();
}
}

/* Method to DELETE an employee from the records */


public void deleteEmployee(Integer EmployeeID) {
Session session = factory.openSession();
Transaction tx = null;

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;

public class StoreDataApp {


public static void main(String[] args) {

CrudManageEmployee crudME = new CrudManageEmployee();


/* Let us have a set of certificates for the first employee */
HashSet setOne = new HashSet();
setOne.add(new Certificate("MCA"));
setOne.add(new Certificate("MBA"));
setOne.add(new Certificate("PMP"));
/* Add employee records in the database */
Integer empID1 = crudME.addEmployee("Manoj", "Kumar", 40000, setOne);

/* Another set of certificates for the second employee */


HashSet setTwo = new HashSet();
setTwo.add(new Certificate("BCA"));
setTwo.add(new Certificate("BA"));

/* Add another employee record in the database */


Integer empID2 = crudME.addEmployee("Dilip", "Kumar", 30000, setTwo);

/* List down all the employees */


crudME.listEmployees();

/* Update employee's salary records */


crudME.updateEmployee(2, 50000);

/* Delete an employee from the database */


crudME.deleteEmployee(2);

/* 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
9. Display Output
Insert

List
MySQL Output
Update
Delete

You might also like