hibernate overview

hibernate overview

Overview

Screen Shot 2020-11-20 at 9.59.51 PM

configuration

  • database connection - hibernate.properties or hibernate.cfg.xml
  • class mapping setup

Session Factory Object

Configuration Object is used to create sessionFactory which in turn configures hibernate for the application using the supplied configuration file and allows for a session object to be instantiated.

ThreadSafe and heavyweight (usually created during app start up)

one database one sessionFactory

Session Object

Session is used to get a physical connection with a database.

Lightweight - designed to be instantiated each time an interaction is needed with the database.

Transaction Object

A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).

Query Object

Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects

Criteria Object

create and execute object oriented criteria queries to retrieve objects.


Configuration

Screen Shot 2020-11-20 at 10.27.55 PM

Session

The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.

State

  • transient

    A new instance of a persistent class, which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate.

  • persistent

    You can make a transient instance persistent by associating it with a Session. A persistent instance has a representation in the database, an identifier value and is associated with a Session.

  • detached

    Once we close the Hibernate Session, the persistent instance will become a detached instance.


Mapping

create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);

<hibernate-mapping>
<class name = "Employee" table = "EMPLOYEE">

<meta attribute = "class-description">
This class contains the employee detail.
</meta>

<id name = "id" type = "int" column = "id">
<generator class="native"/>
</id>

<property name = "firstName" column = "first_name" type = "string"/>
<property name = "lastName" column = "last_name" type = "string"/>
<property name = "salary" column = "salary" type = "int"/>

</class>
</hibernate-mapping>

Sample


public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {

try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}

ManageEmployee ME = new ManageEmployee();

/* Add few employee records in database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000);

/* List down all the employees */
ME.listEmployees();

/* Update employee's records */
ME.updateEmployee(empID1, 5000);

/* Delete an employee from the database */
ME.deleteEmployee(empID2);

/* List down new list of the employees */
ME.listEmployees();
}

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

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