Hibernate Complete Notes

Structured study notes covering JDBC limitations, ORM, JPA, Hibernate architecture, configuration, mappings, HQL, caching, Spring integration, JPA architecture, annotations and bean conventions.

JDBC & Hibernate Introduction

HIBERNATE

What is JDBC?

  • JDBC stands for Java Database Connectivity.
  • It provides a set of Java API for accessing the relational databases from Java

program.

  • These Java APIs enables Java programs to execute SQL statements and

interact with any SQL compliant database.

  • JDBC provides a flexible architecture to write a database independent

application that can run on different platforms and interact with different DBMS without any modification.

LIMITATIONS OF JDBC

  • Jdbc code Database software dependent persistent logic.
  • Changing software complex process.
  • Jdbc code is not portable code across the multiple database software’s.
  • We need to object notation data to simple value to use them in persistence logic.
  • Exception handling is mandatory.
  • There is no support versioning and time stamping.
  • There is no proper transaction management support.
  • Does not support object level relationships.
  • Boiler plate code problem

The code that repeats multiple programs either with minimum code change or no change is called Boiler plate code problem To develop Persistent logic we use Hibernate. Persistence: - The process of storing and maintaining the data for a long time is called persistence. Any service sector project without Persistence

  • Hospital Management system
  • Bank project
  • Donor payments
  • Employee services

1. Persistence store File database software 2.Persistent data File data, Database table records 3.Persistence Operations

CURD/CRUD/SCUD

5. Persistence logic Ex:- I/O streams code, JDBC code, hibernate code. 6. Persistence framework/technologies

JDBC Hibernate Persistence technologies/frame works are given to develop the persistence logic for performing persistence operations on persistent data of persistent store. Languages are raw materials Technologies are semi finish product. Frame works are called fully finished product.

  • Rice Granules, Wheat Granules Programming Languages
  • Rice powder, Wheat Powder Technologies
  • Maggi noodles, Patanjali Noodles Frame works

Persistence logic Java App -------------- I/O Stream------------------------ Flat files Serialization & Deserialization Writing data Reading data Java----------JDBC o-mappings----------------- DB/ The Object -Relational Impedance Mismatch Object-Relational Impedance Mismatch' (sometimes called the 'paradigm mismatch') is just a fancy way of saying that object models and relational models do not work very well together. RDBMSs represent data in a tabular format (a spreadsheet is a good visualization for those not familiar with RDBMSs), whereas object-oriented languages, such as Java, represent it as an interconnected graph of objects. Loading and storing graphs of objects using a tabular relational database exposes us to 5 mismatch problems. The Object-Relational Mapping (ORM) is the solution to handle all the above impedance mismatches.

ORM, JPA & Hibernate

What is ORM?

ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java, C#, etc. An ORM system has the following advantages over plain JDBC: An ORM solution consists of the following four entities: Hibernate is a Java framework that simplifies the development of Java application to interact with the database. It is an open source, lightweight, ORM (Object Relational Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for data persistence. Open source: - Not only free, source code also visible. POJO/POJI Model ORM Tool An ORM tool simplifies the data creation, data manipulation and data access. It is a programming technique that maps the object to the data stored in the database. The ORM tool internally uses the JDBC API to interact with the database.

What is JPA?

Java Persistence API (JPA) is a Java specification that provides certain functionality and standard to ORM tools. The javax.persistence package contains the JPA classes and interfaces.

Hibernate Advantages

  • Open Source and Lightweight

Hibernate framework is open source under the LGPL license and lightweight.

  • Fast Performance

The performance of hibernate framework is fast because cache is internally used in hibernate framework. There are two types of cache in hibernate framework first level cache and second level

cache. First level cache is enabled by default.

  • Database Independent Query

HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the database independent queries. So you don't need to write database specific queries. Before Hibernate, if database is changed for the project, we need to change the SQL query as well that leads to the maintenance problem.

  • Automatic Table Creation

Hibernate framework provides the facility to create the tables of the database automatically. So there is no need to create tables in the database manually. Simplifies Complex Join Fetching data from multiple tables is easy in hibernate framework.

  • Provides Query Statistics and Database Status

Hibernate supports Query cache and provide statistics about query and database status.

HIBERNATE ARCHITECTURE

Hibernate has a layered architecture which helps the user to operate with out having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application. Following is a very high level view of the Hibernate Application Architecture.

Hibernate Architecture & Core Objects

Following is a detailed view of the Hibernate Application Architecture with its important core classes. Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers. Java persistence API is a collection of classes and methods to persistency store the vast amounts of data into a database. JPA is a frame work for managing relational

data in Java applications ,while Hibernate is a specific implementation of JPA CSO Ideally JPA & Hibernate can’t be Directly compared .In another words Hibernate is one of the most popular Frame works that implements JPA. Hibernate implements JPA through hibernate Annotation and entity manger library that are implemented on top of Hibernate core Libraries. Configuration Object The Configuration object is the first Hibernate object you create in any Hibernate application. It is usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate. The Configuration object provides two keys components:

  • Database Connection: This is handled through one or more configuration files

supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.

  • Class Mapping Setup: This component creates the connection between the Java

classes and database tables. SessionFactory Object Configuration object is used to create a SessionFactory object which in turn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application. The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So, if you are using multiple databases, then you would have to create multiple SessionFactory objects. Session Object A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object. 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.

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). This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code. Query Object

Query objects use SQL or Hibernate Query Language (HQL) string 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 finally to execute the query.

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

Configuration & Object Lifecycle

HIBERNATE - CONFIGURATION

  

Hibernate object life cycle

Persistent objects are synchronized with DB.

Hibernate Object are 3 States.

  • Transient
  • Persistent
  • Detached

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.

Hibernate Mapping

Inheritance Mapping

Mapping Name Attribute name

Table per Hierarchy Inheritance singleton, Discrimination column, single Table Table per sub class Inheritance Type .Joined, @ primary key column (name=”IN”) 2 Table &PK & F K Table per class/ Table per Concrete class @Inheritance Type . table _per class, Independent table

Table Per Hierarchy

In table per hierarchy mapping, single table is required to map the whole hierarchy, an extra column (known as discriminator column) is added to identify the class. But nullable values are stored in the table

Table Per Concrete class

In case of table per concrete class, tables are created as per class. But duplicate column is added in subclass tables.

Table Per Subclass

In this strategy, tables are created as per class but related by foreign key. So there are no duplicate columns. Association Mapping Mapping Name Example One-one Employee & his personal details One-many Department - employee Many-one Employee & Their protect Many-many Employee-course

one to one mapping

There are two ways to perform one to one mapping in hibernate:

  • By many-to-one element (using unique="true" attribute)
  • By one-to-one element

Here, we are going to perform one to one mapping by one-to-one element. In such case, no foreign key is created in the primary table.

One to Many mapping

If the persistent class has list object that contains the entity reference, we need to use one -to-many association to map the list element. Here, we are using the scenario of Forum where one question has multiple answers.

Many to One Mapping

In many to one mapping, various attributes can be referred to one attribute only. In this example, every employee has one company address only and one address belongs to many employees.

Many to Many Mapping

We can map many to many relation either using list, set, bag, map, etc. Cascade In Cascade after one operation ( save, update ,&delete) is done ,it decides whether it need to call other operations ( save, update, & delete) on another entities which has relationship with each other.

Collection Mapping in Hibernate

We can map collection elements of Persistent class in Hibernate. You need to declare the type of collection in Persistent class from one of the following types:

  • java.util.List
  • java.util.Set
  • java.util.SortedSet
  • java.util.Map
  • java.util.SortedMap
  • java.util.Collection
  • or write the implementation of org.hibernate.usertype.UserCollectionType

Transactions & Fetching

Transaction Management

A transaction simply represents a unit of work. In such case, if one step fails, the whole transaction fails (which is termed as atomicity). A transaction can be described by ACID properties (Atomicity, Consistency, Isolation and Durability).

Fetching strategies

Hibernate uses a fetching strategy to retrieve associate objects if the application needs to navigate the association. Fetch strategies can be declared in the O/R mapping Meta data or override by a particular HQL or criteria query. Fetch Type is an enumerated type in the Java Persistence API (JPA) that specifies whether the field or property should be lazily loaded or eagerly loaded. It is used in the javax.persistence.FetchType enum. In Hibernate, the FetchType is used to specify the fetching strategy to be used for an association. The FetchType can be specified for associations at the time of mapping the association. There are two FetchType options available: LAZY and EAGER.

Lazy Loading

The Lazy load means loading child objects while loading the parent object. This setting must be done in Hibernate mapping xml/parent file of the parent class. Lazy settings decides whether to load child objects while loading the parent objects.

By default the lazy loading of the child object is true if lazy =true means not to load the child objects if lazy = false means load the child objects. Parent child NTL False True Lazy Loading True False

Load VS Get

To fetch the data load will use proxy .if no data is available in proxy load will throw a NullPointerException. Get to fetch the data it will use database and returns null if no data is available.

Hibernate Query Language (HQL)

Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't depends on the table of the database. Instead of table name, we use class name in HQL. So it is database independent query language. Advantage of HQL There are many advantages of HQL. They are as follows:

  • database independent
  • supports polymorphic queries
  • easy to learn for Java Programmer

Query Interface

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

interface.

  • The query interface provides many methods.
  • There is given commonly used methods:

HQL & HCQL

By default the lazy loading of the child object is true if lazy =true means not to load the child objects if lazy = false means load the child objects. Parent child NTL False True Lazy Loading True False

Load VS Get

To fetch the data load will use proxy .if no data is available in proxy load will throw a NullPointerException. Get to fetch the data it will use database and returns null if no data is available.

Hibernate Query Language (HQL)

Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't depends on the table of the database. Instead of table name, we use class name in HQL. So it is database independent query language. Advantage of HQL There are many advantages of HQL. They are as follows:

  • database independent
  • supports polymorphic queries
  • easy to learn for Java Programmer

Query Interface

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

interface.

  • The query interface provides many methods.
  • There is given commonly used methods:

HCQL (Hibernate Criteria Query Language)

The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the specific criteria. The Criteria interface provides methods to apply crit eria such as retreiving all the records of table whose salary is greater than 50000 etc. Advantage of HCQL The HCQL provides methods to add criteria, so it is easy for the java programmer to add criteria. The java programmer is able to add many criteria on 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 Session interface. Restrictions class Restrictions class provides methods tha t can be used as Criterion. The commonly used methods of Restrictions class are as follows:

Named Queries & Caching

Hibernate Named Query

The hibernate named query is way to use any query by some meaningful name. It is like using alias names. The Hibernate framework provides the concept of named queries so that application programmer needs not to scatter queries to all the java code. There are two ways to define the named query in hibernate:

  • by annotation
  • by mapping file.

Caching

Hibernate caching improves the performance of the application by pooling the object in the cache. It is useful when we have to fetch the same data multiple times. There are mainly two types of caching:

  • First Level Cache
  • Second Level Cache

First Level Cache

Session object holds the first level cache data. It is enabled by default. The first level cache data will not be available to entire application. An application can use many session object.

Second Level Cache

Session Factory object holds the second level cache data. The data stored in the second level cache will be available to entire application. But we need to enable it explicitly.

  • EH (Easy Hibernate) Cache
  • Swarm Cache
  • OS Cache
  • JBoss Cache

The cache-usage property can be applied to class or collection level in hbm.xml file. The example to define cache usage is given below: 1. <cache usage="read-only" /> Let's see the second level cache implementation and cache usage.

Stored Procedures & Parameters

Calling Stored procedure

@ Named Native Query (name =””,query=”{call stored procedure (?,?,?)}”
Result mapping =” ExtractSPesult “);
@ Sql Result mapping ( value={ @ result mapping (name=” app ums extract SP result “entity ={ @
Entity Result (Entity class =Domain.class,fund={
@Field result (name =”event product_id
Column=” event-product_id”);
})

Passing parameters in HQL in two ways

1. Positional parameters ? 2. Named parameters : name.

Hibernate & Spring Integration

Hibernate and Spring Integration

We can simply integrate hibernate application with spring application. In hibernates framework, we provide the entire database information hibernate.cfg.xml file. But if we are going to integrate the hibernate application with spring, we don't need to create the hibernate.cfg.xml file. We can provide all the information in the applicationContext.xml file Advantage of Spring framework with hibernate The Spring framework provides HibernateTemplate class, so you don't need to follow so many steps like create Configuration, BuildSessionFactory, Session, beginning and committing transaction etc. So it saves a lot of code.

Spring Data JPA & JPA

Spring Data JPA Tutorial

Spring Data JPA API provides JpaTemplate class to integrate

spring application with JPA. JPA (Java Persistent API) is the sun specification for persisting objects in the enterprise application. It is currently used as the replacement for complex entity beans. The implementation of JPA specification is provided by many vendors such as:

  • Hibernate
  • Toplink
  • iBatis
  • OpenJPA etc.

JPA

Java Persistence API is a collection of classes and methods to persistently store the vast amounts of data into a database. This tutorial provides you the basic understanding of Persistence (storing the copy of database object into temporary memory), and we will learn the understanding of JAVA Persistence API (JPA). Any enterprise application performs database operations by storing and retrieving vast amounts of data. Despite all the available technologies for storage management, application developers normally struggle to perform database operations efficiently. Generally, Java developers use lots of code, or use the proprietary framework to interact with the database, whereas using JPA, the burden of interacting with the database reduces significantly. It forms a bridge between object models (Java program) and relational models (database program).

What is JPA?

Java Persistence API is a collection of classes and methods to persistently store the vast amounts of data into a database which is provided by the Oracle Corporation. Where to use JPA? To reduce the burden of writing codes for relational object management, a programmer follows the ‘JPA Provider’ framework, which allows easy interaction with database instance. Here the required framework is taken over by JPA.

JPA History

Earlier versions of EJB, defined persistence layer combined with business logic layer using javax.ejb.EntityBean Interface.

  • While introducing EJB 3.0, the persistence layer was separated and specified as JPA

1.0 (Java Persistence API). The specifications of this API were released along with the specifications of JAVA EE5 on May 11, 2006 using JSR 220.

  • JPA 2.0 was released with the specifications of JAVA EE6 on December 10, 2009 as a

part of Java Community Process JSR 317.

  • JPA 2.1 was released with the specification of JAVA EE7 on April 22, 2013 using JSR

338.

JPA Providers

JPA is an open source API, therefore various enterprise vendors such as Oracle, Redhat, Eclipse, etc. provide new products by adding the JPA persistence flavor in them. Some of these products include: Hibernate, Eclipselink, Toplink, Spring Data JPA, etc.

JPA - Architecture

Java Persistence API is a source to store business entities as relational entities. It shows how to define a PLAIN OLD JAVA OBJECT (POJO) as an entity and how to manage entities with relations. Class Level Architecture The following image shows the class level architecture of JPA. It shows the core classes and interfaces of JPA.

JPA Architecture & Relationships

The above classes and interfaces are used for storing entities into a database as a record. They help programmers by reducing their efforts to write codes for storing data into a database so that they can concentrate on more important activities such as writing codes for mapping the classes with database tables.

JPA Class Relationships

In the above architecture, the relations between the classes and interfaces belong to the javax.persistence package. The following diagram shows the relationship between them.

JPA Unit Relationships

UnitDescription
EntityManagerFactoryA factory class of EntityManager. It creates and manages multiple EntityManager instances.
EntityManagerAn interface that manages persistence operations on objects and works like a factory for Query instances.
EntityPersistence objects stored as records in the database.
EntityTransactionHas a one-to-one relationship with EntityManager; operations are maintained by EntityTransaction.
PersistenceContains static methods to obtain an EntityManagerFactory instance.
QueryAn interface implemented by each JPA vendor to obtain relational objects that meet criteria.

JPA Class Relationships

The source diagram shows the relationships among EntityManagerFactory, EntityManager, EntityTransaction, Query, Persistence and Entity in the javax.persistence package.

  • EntityManagerFactory to EntityManager: one-to-many.
  • EntityManager to EntityTransaction: one-to-one.
  • EntityManager to Query: one-to-many.
  • EntityManager to Entity: one-to-many.

ORM Architecture

The ORM architecture in the source explains how object data is stored in a relational database through three phases.

Phase 1 - Object Data Phase

Contains POJO classes, service interfaces and classes. It is the main business component layer containing business logic operations and attributes. The example describes an Employee POJO with ID, name, salary and designation, together with DAO/Service methods such as create, find and delete employee.

Phase 2 - Mapping / Persistence Phase

  • JPA Provider: Vendor product containing the JPA flavor, for example EclipseLink, TopLink and Hibernate.
  • Mapping file: ORM.xml containing mapping configuration between POJO data and relational database data.
  • JPA Loader: Works like cache memory and can load relational grid data so service classes can interact with POJO attributes.
  • Object Grid: Temporary location that stores a copy of relational data. Queries first affect the object grid and changes reach the main database after commit.

Phase 3 - Relational Data Phase

The third phase contains relational data logically connected to the business component. The source describes committing modified data to the database and retrieving data through the same three-phase mechanism.

The programmatic interaction of these three phases is described as object-relational mapping.

Annotations & Bean Conventions

Annotations

Annotations

AnnotationDescription
@EntityDeclares a class as an entity or table.
@TableSpecifies the table name.
@BasicSpecifies non-constraint fields explicitly.
@EmbeddedSpecifies properties of a class or entity whose value is an instance of an embeddable class.
@IdSpecifies the identity / primary-key property of the class.
@GeneratedValueSpecifies how an identity attribute is initialized, such as automatic, manual, or from a sequence table.
@TransientSpecifies a property that is not persistent and is never stored in the database.
@ColumnSpecifies a column or attribute for persistence.
@SequenceGeneratorSpecifies the value generator used with @GeneratedValue and creates a sequence.
@TableGeneratorSpecifies a value generator for @GeneratedValue and creates a table for value generation.
@AccessTypeSets the access type; FIELD uses field access and PROPERTY uses property access.
@JoinColumnSpecifies an entity association or entity collection, used in many-to-one and one-to-many associations.
@UniqueConstraintSpecifies a unique constraint for a primary or secondary table.
@ColumnResultReferences the name of a column in an SQL query using a select clause.
@ManyToManyDefines a many-to-many relationship between join tables.
@ManyToOneDefines a many-to-one relationship between join tables.
@OneToManyDefines a one-to-many relationship between join tables.
@OneToOneDefines a one-to-one relationship between join tables.
@NamedQueriesSpecifies a list of named queries.
@NamedQuerySpecifies a query using a static name.

Bean Conventions

  • A bean contains the default constructor or a file containing a serialized instance, allowing the bean to be instantiated.
  • Bean properties can be separated into Boolean and non-Boolean properties.
  • Non-Boolean properties contain getter and setter methods.
  • Boolean properties contain a setter and an is method.
  • Getter methods start with lowercase get followed by a field name beginning with a capital letter; for example, getSalary().
  • Setter methods start with lowercase set followed by a field name beginning with a capital letter and accept the value to set; for example, setSalary(double sal).
  • For a Boolean property, the is method checks whether the value is true or false; for example, isEmpty().