Java Persistence with Hibernate and JPA

Java Persistence with Hibernate and JPA

Hibernate Framework

  • Hibernate is a Java framework that simplifies the interaction of Java applications with databases.
  • It is an open-source, lightweight Object-Relational Mapping (ORM) tool, created by Gavin King in 2001.
  • Hibernate serves as a high-performance Object/Relational persistence and query service for Java applications.
  • It implements Java Persistence API (JPA) specifications for data persistence.
  • It is licensed under the GNU Lesser General Public License (LGPL) and is available for free download.
  • Hibernate handles mapping from Java classes to database tables and Java data types to SQL data types.

Pros and Cons of JDBC

Pros of JDBC

  • Clean and simple SQL processing.
  • Good performance with large data.
  • Suitable for small applications.
  • Simple syntax, easy to learn.

Cons of JDBC

  • Complex in large projects.
  • Large programming overhead.
  • No encapsulation.
  • Difficult to implement MVC concept.
  • Queries are DBMS specific.

Why Object Relational Mapping (ORM)?

  • ORM addresses the mismatch between object models and relational databases.
  • RDBMSs represent data in tables.
  • Object-oriented languages like Java and C# represent data as interconnected object graphs.

Java Class and RDBMS Table Example

  • Java Class:

    public class Employee {
        private int id;
        private String first_name;
        private String last_name;
        private int salary;
    public Employee() {}
    
    public Employee(String fname, String lname, int salary) {
        this.first_name = fname;
        this.last_name = lname;
        this.salary = salary;
    }
    
    public int getId() { return id; }
    public String getFirstName() { return first_name; }
    public String getLastName() { return last_name; }
    public int getSalary() { return salary; }
    
    }
  • RDBMS table:

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

Problems between Object Link and Table

  • Difficulties arise when modifying the database design after application development.
  • Challenges exist in loading and storing objects in a relational database.

Mismatches

  1. Granularity: Object models may have more classes than corresponding database tables.
  2. Inheritance: RDBMSs lack a direct equivalent to inheritance in object-oriented languages.
  3. Identity: RDBMS defines a single notion of sameness (primary key), while Java defines object identity (a==b) and object equality (a.equals(b)).
  4. Associations: Object-oriented languages use object references for associations, whereas RDBMS uses foreign key columns.
  5. Navigation: Accessing objects in Java and RDBMS is fundamentally different.

ORM

  • ORM is a programming technique that maps objects to data stored in a database.
  • An ORM tool simplifies data creation, manipulation, and access.
  • The ORM tool uses the JDBC API internally to interact with the database.

Advantages of Hibernate Framework

  1. Open Source and Lightweight: Hibernate is open source under the LGPL license and lightweight.
  2. Fast Performance: Hibernate uses internal caching (first and second-level caches), with the first-level cache enabled by default.
  3. Database Independent Query: HQL (Hibernate Query Language) is an object-oriented version of SQL, generating database-independent queries. It reduces maintenance issues when changing databases.
  4. Automatic Table Creation: Hibernate can automatically create database tables, eliminating manual table creation.
  5. Simplifies Complex Join Fetching: Easier to fetch data from multiple tables.

Supported Databases

  • HSQL Database Engine
  • DB2/NT
  • MySQL
  • PostgreSQL
  • FrontBase
  • Oracle
  • Microsoft SQL Server Database
  • Sybase SQL Server
  • Informix Dynamic Server

Supported Technologies

  • XDoclet Spring
  • J2EE
  • Eclipse plug-ins
  • Maven

Hibernate Architecture

  • Hibernate architecture includes persistent objects, session factory, transaction factory, connection factory, session, transaction, etc.
  • Categorized into four layers:
    • Java application layer
    • Hibernate framework layer
    • Backend API layer
    • Database layer

IOW Level Architecture

  • Diagram illustrates the high-level architecture of Hibernate with mapping and configuration files.

Elements of Hibernate Architecture

Core Objects

  • Session Factory
  • Transaction
  • Session
  • Query
  • Criteria

Java APIs

  • JDBC (Java Database Connectivity)
  • JTA (Java Transaction API)
  • JNDI (Java Naming Directory Interface).

Configuration

  • First Hibernate object created in any Hibernate application.
  • Usually created once during application initialization.
  • Represents a configuration or properties file required by Hibernate.
  • Key components:
    • Database Connection: Handled through configuration files (hibernate.properties and hibernate.cfg.xml).
    • Class Mapping Setup: Creates the connection between Java classes and database tables.

SessionFactory

  • Configuration object is used to create a SessionFactory object.
  • SessionFactory configures Hibernate for the application using the configuration file and allows for the instantiation of Session objects.
  • SessionFactory is thread-safe and used by all application threads.
  • SessionFactory is a heavyweight object, created during application start-up and kept for later use.
  • Need one SessionFactory object per database with a separate configuration file.
  • Using multiple databases requires creating multiple SessionFactory objects.

Session

  • Session is used to get a physical connection with a database.
  • Session object is lightweight and designed to be instantiated each time an interaction with the database is needed.
  • Persistent objects are saved and retrieved through a Session object.
  • Session objects should not be kept open for extended periods as they are not usually thread-safe; they should be created and destroyed as needed.

Transaction

  • Represents a unit of work with the database, supported by most RDBMSs.
  • Transactions in Hibernate are handled by an underlying transaction manager (from JDBC or JTA).
  • Optional object; Hibernate applications may choose not to use this interface, instead managing transactions in their application code.

Query

  • Query objects use SQL or Hibernate Query Language (HQL) strings to retrieve data from the database and create objects.
  • A Query instance is used to bind query parameters, limit the number of results returned by the query, and execute the query.

Criteria

  • Criteria objects are used to create and execute object-oriented criteria queries to retrieve objects.

Hibernate using XML in Eclipse

  • Steps to create a simple Hibernate application in Eclipse IDE:
    1. Create a Java project.
    2. Add JAR files for Hibernate.
    3. Create the Persistent class.
    4. Create Table.
    5. Create the mapping file for Persistent class.
    6. Create the Configuration file.
    7. Create the Application class to retrieve or store persistent objects.
    8. Run the application.

Steps 1 & 2

  1. Create the Java project: File Menu - New - Project - Java Project.
  2. Add JAR files for hibernate: Right click on your project - Build path - Add external archives. Select all the jar files. Add the mysql-connector.jar file to connect with MySQL databases.

Step 3: Create the Persistent Class

  • A POJO (Plain Old Java Object) is a Java object that doesn't extend or implement specialized classes and interfaces.

  • To create the persistent class, Right click on src - New - Class - specify the class with package name (e.g., com.pu) - finish.

    com.pu.Employee.java

  • Design a class to be persisted by Hibernate.

  • It is important to provide JavaBeans compliant code as well as one attribute, which would work as index like id attribute in the Employee class.

Step 4: Create Database Tables

  • Create tables in your database corresponding to each object you want to provide persistence for.
  • The example shows creating the EMPLOYEE table in RDBMS.

Step 5: Create the Mapping File for Persistent Class

  • Mapping file name convention: class_name.hbm.xml
  • Elements of the mapping file:
    • hibernate-mapping: Root element, contains all mapping elements and <class> elements.
    • class: Specifies the Persistent class. Used to define specific mappings from Java classes to database tables.
      • name attribute: Java class name.
      • table attribute: Database table name.
    • meta: Optional element to create class description.
    • id: Maps the unique ID attribute in the class to the primary key of the database table.
      • name attribute: Refers to the property in the class.
      • column attribute: Refers to the column in the database table.
      • type attribute: Holds the Hibernate mapping type, which converts from Java to SQL data type.
    • generator: Generates the primary key. Classes include assigned, increment, hilo, sequence, native, etc.
      • class attribute: Set to native to let Hibernate pick up either identity, sequence, or hilo algorithm to create primary key depending on the database capabilities.

Step 6: Create the Configuration File

  • Hibernate requires configuration settings related to the database and other parameters, supplied as a Java properties file (hibernate.properties) or XML file (hibernate.cfg.xml).
  • The configuration file contains database information such as connection URL, driver class, username, password, etc.
  • To create the configuration file, right-click on src - new - file, then specify the configuration file name (e.g., hibernate.cfg.xml).

Step 7: Create the Application Class

  • This class retrieves or stores the persistent object.

Step 8: Run the Application

  • Before running the application, ensure that the directory structure is correct.
  • Run the application by right-clicking on the StoreData class and selecting Run As - Java Application.

Hibernate Properties

Sr.No.PropertiesDescription
1hibernate.dialectGenerates appropriate SQL for the chosen database.
2hibernate.connection.driver_classThe JDBC driver class.
3hibernate.connection.urlThe JDBC URL to the database instance.
4hibernate.connection.usernameThe database username.
5hibernate.connection.passwordThe database password.
6hibernate.connection.pool_sizeLimits the number of connections waiting in the Hibernate database connection pool.
7hibernate.connection.autocommitAllows autocommit mode for the JDBC connection.

Databases Dialect Property

Sr.No.DatabaseDialect Property
1DB2org.hibernate.dialect.DB2Dialect
2HSQLDBorg.hibernate.dialect.HSQLDialect
3HypersonicSQLorg.hibernate.dialect.HSQLDialect
4Informixorg.hibernate.dialect.InformixDialect
5Ingresorg.hibernate.dialect.IngresDialect
6Interbaseorg.hibernate.dialect.InterbaseDialect
7Microsoft SQL Serverorg.hibernate.dialect.SQLServerDialect
8MySQLorg.hibernate.dialect.MySQLDialect

Example: 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>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/god?characterEncoding=latin1</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">admin123</property>
        <property name="connection.pool_size">3</property>
        <property name="current_session_context_class">thread</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update </property>
        <mapping resource="employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Hibernate using Annotation

  • Hibernate applications can be created using annotations such as @Entity, @Id, @Table, etc.
  • Hibernate Annotations are based on the JPA 2 specification and support all its features.
  • JPA annotations are defined in the javax.persistence package.
  • The advantage of using Hibernate annotations is that no mapping (hbm) file is required.

Example to create the hibernate application with Annotation

Steps

  1. Create the Maven Project
  2. Add project information and configuration in pom.xml file
  3. Create Persistence class.
  4. Create the Configuration file
  5. Create the class that retrieves or stores the persistent object
  6. Run the application

1) Create the Maven Project

2) Add project information and configuration in pom.xml file

  • Add the below dependencies between <dependencies>....</dependencies> tag. These dependencies are used to add the jar files in Maven project.

  • Example:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.1.6.Final</version>
    </dependency>
    
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.31</version>
    </dependency>
    

3) Create the Persistence class.

  • Annotations used:
    • @Entity: Marks the class as an entity.
    • @Table: Specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, Hibernate will use the class name as the table name by default.
    • @Id: Marks the identifier for this entity.
    • @Column: Specifies the details of the column for this property or field. If @Column annotation is not specified, property name will be used as the column name by default.

4) Create the Configuration file

5) Create the class that retrieves or stores the persistent object.

6) Run the application

Web Application with Hibernate (using XML)

  • Uses JSP for presentation logic, Bean class for representing data, and DAO class for database codes.

Example to create web application using hibernate

  • Example demonstrates inserting user records into the database using a registration form.

  • Files involved:

    • index.jsp: Gets input from the user and sends it to the register.jsp file using the post method.

    • User.java: The simple bean class representing the Persistent class in hibernate.

    • UserDao.java: Dao class, containing method to store the instance of User class.

    • register.jsp: Gets all request parameters and store this information into an object of User class. Further, it calls the register method of UserDao class passing the User class object.

    • user.hbm.xml: Maps the User class with the table of the database.

    • hibernate.cfg.xml: The configuration file, containing informations about the database and mapping file.

Output

Generator Classes in Hibernate

  • The <generator> class is a sub-element of id, used to generate unique identifiers for objects of persistent classes.
  • All generator classes implement the org.hibernate.id.IdentifierGenerator interface.
  • Hibernate provides built-in generator classes:
    • assigned
    • increment
    • sequence
    • hilo
    • native
    • identity
    • seqhilo
    • uuid id

SQL Dialects in Hibernate

  • Dialect specifies the type of database used in Hibernate, so that Hibernate can generate appropriate SQL statements.

  • Configuration of SQL dialect is required for connecting any Hibernate application with the database.

  • The syntax of SQL dialect is:

    <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
    

List of SQL Dialects

RDBMSDialect Property
Oracle (any version)org.hibernate.dialect.OracleDialect
Oracle9iorg.hibernate.dialect.Oracle9iDialect
Oracle10gorg.hibernate.dialect.Oracle10gDialect
MySQLorg.hibernate.dialect.MySQLDialect
MySQL with InnoDBorg.hibernate.dialect.MySQLInnoDBDialect
MySQL with MyISAMorg.hibernate.dialect.MySQLMyISAMDialect
DB2org.hibernate.dialect.DB2Dialect
Microsoft SQL Serverorg.hibernate.dialect.SQLServerDialect
PostgreSQLorg.hibernate.dialect.PostgreSQLDialect

HQL Querying

Definition

  • Hibernate Query Language (HQL) is similar to SQL, but it does not depend on the database table.
  • Instead of table names, HQL uses class names.
  • Therefore, it is a database-independent query language.

Advantages of HQL

  • Database independent.
  • Supports polymorphic queries.
  • Easy to learn for Java programmers.

Query Interface

  • It is an object-oriented representation of a Hibernate query.
  • The Query object can be obtained by calling the createQuery() method of the Session interface.

Commonly Used Methods

  • public int executeUpdate()

    • Used to execute update or delete queries.
  • public List list()

    • Returns the result of the relation as a list.
  • public Query setFirstResult(int rowno)

    • Specifies the row number from where record retrieval will start.
  • public Query setMaxResult(int rowno)

    • Specifies the number of records to be retrieved.
  • public Query setParameter(int position, Object value)

    • Sets the value to the JDBC style query parameter.
  • public Query setParameter(String name, Object value)

    • Sets the value to a named query parameter.

Examples

  • Example of HQL to get all the records:

    Query query=session.createQuery("from Emp");//persistent class name is Emp
    List list=query.list();
    
  • Example of HQL update query:

    Transaction tx=session.beginTransaction();
    Query q=session.createQuery("update User set name=:n where id=:i");
    q.setParameter("n","Udit Kumar");
    q.setParameter("i",111);
    int status=q.executeUpdate();
    System.out.println(status);
    tx.commit();
    
  • Example of HQL delete query:

    Query query=session.createQuery("delete from Emp where id=100"); //specifying class name (Emp) not table name
    query.executeUpdate();
    
  • HQL with Aggregate functions: Call avg(), min(), max() etc. aggregate functions by HQL.

HCQL Hibernate Criteria Query Language

HCQL - Definition

  • The Hibernate Criteria Query Language (HCQL) is used to fetch records based on specific criteria.
  • The Criteria interface provides methods to apply criteria such as retrieving all records of a table where the salary is greater than 50000, etc.

Advantage of HCQL

  • HCQL provides methods to add criteria, making it easy for Java programmers to add criteria.
  • A Java programmer can add many criteria to a query.

Criteria Interface

  • The Criteria interface provides many methods to specify criteria.

    • The object of Criteria can be obtained by calling the createCriteria() method of the Session interface.
  • Syntax of createCriteria() method of the Session interface:

    public Criteria createCriteria(Class c)
    

Commonly Used Methods of the Criteria Interface:

  • public Criteria add(Criterion c)

    • Used to add restrictions.
  • public Criteria addOrder(Order o)

    • Specifies ordering.
  • public Criteria setFirstResult(int firstResult)

    • Specifies the first record number to be retrieved.
  • public Criteria setMaxResult(int totalResult)

    • Specifies the total number of records to be retrieved.
  • public List list()

    • Returns a list containing objects.

Restrictions Class

  • The Restrictions class provides methods that can be used as Criterion.

Order Class

  • The Order class represents an order.

Examples

  • Examples of HCQL:

    • To get all records:

      Criteria c=session.createCriteria(Emp.class);//passing Class class argument
      List list=c.list();
      
    • To get the 10th to 20th record:

      Criteria c=session.createCriteria(Emp.class);
      c.setFirstResult(10);
      c.setMaxResult(20);
      List list=c.list();
      
    • To get the records whose salary is greater than 10000:

      Criteria c=session.createCriteria(Emp.class);
      c.add(Restrictions.gt("salary",10000));//salary is the property name
      List list=c.list();
      
  • HCQL with Projection: Fetch data of a particular column by projection such as name, etc.

Hibernate Named Query

Definition

  • A way to use any query by a meaningful name, like using alias names.
  • Hibernate provides the concept of named queries so that developers do not need to scatter queries throughout the Java code.