0% found this document useful (0 votes)
70 views38 pages

EJ Unit 5

The document discusses object-relational mapping and persistence in Java. It describes several standards for persistence in Java including serialization, JDBC, EJB 2.0 entity beans, JDO, and the Java Persistence API (JPA). JPA provides a standard for object-relational mapping in Java that overcomes limitations of previous standards like complex mappings, performance issues, and lack of portability. The document also discusses the need for object-relational mapping to separate application logic from data access code for better system architecture, reusability, and ease of maintenance.

Uploaded by

Yexo Kaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views38 pages

EJ Unit 5

The document discusses object-relational mapping and persistence in Java. It describes several standards for persistence in Java including serialization, JDBC, EJB 2.0 entity beans, JDO, and the Java Persistence API (JPA). JPA provides a standard for object-relational mapping in Java that overcomes limitations of previous standards like complex mappings, performance issues, and lack of portability. The document also discusses the need for object-relational mapping to separate application logic from data access code for better system architecture, reusability, and ease of maintenance.

Uploaded by

Yexo Kaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Enterprise Java

MODULE-5: ORM, JPA and Hibernate

Compiled by: Prof. Beena Kapadia


Vidyalankar School of [email protected]
Information Technology
Wadala (E), Mumbai
www.vsit.edu.in
Certificate
This is to certify that the e-book titled “Enterprise java” comprises
all elementary learning tools for a better understating of the relevant concepts. This
e-book is comprehensively compiled as per the predefined eight parameters and
guidelines.

Signature
Date: 09-07-2019
Ms. Payal Shah
Assistant Professor
Department of IT

DISCLAIMER: The information contained in this e-book is compiled and distributed for
educational purposes only. This e-book has been designed to help learners understand
relevant concepts with a more dynamic interface. The compiler of this e-book and
Vidyalankar Institute of Technology give full and due credit to the authors of the contents,
developers and all websites from wherever information has been sourced. We acknowledge
our gratitude towards the websites YouTube, Wikipedia, and Google search engine. No
commercial benefits are being drawn from this project.
Unit V ORM, JPA and Hibernate

Contents:

 Persistence, Object/Relational Mapping And JPA: What is Persistence? Persistence in


Java, Current Persistence Standards in Java, Why another Persistence Standards?
Object/Relational Mapping,
 Introduction to Java Persistence API: The Java Persistence API, JPA, ORM, Database
and the Application, Architecture of JPA, How JPA Works? JPA Specifications.
 Writing JPA Application: Application Requirement Specifications, Software
Requirements, The Application Development Approach, Creating Database And Tables in
Mysql, Creating a Web Application, Adding the Required Library Files, Creating a
Javabean Class, Creating Persistence Unit [Persistence.Xml], Creating JSPS, The JPA
Application Structure, Running The JPA Application.
 Introduction to Hibernate: What is Hibernate? Why Hibernate? Hibernate, Database
and The Application, Components of Hibernate, Architecture of Hibernate, How
Hibernate Works?
 Writing Hibernate Application: Application Requirement Specifications, Software
Requirements, The Application Development Approach, Creating Database and Tables in
Mysql, Creating a Web Application, Adding The Required Library Files, Creating a
Javabean Class, Creating Hibernate Configuration File, Adding a Mapping Class, Creating
JSPS, Running The Hibernate Application.

Recommended Books

Books:

B1 Java EE 7 For Beginners by Sharanam Shah, Vaishali Shah

Prerequisites & Linking


Unit V Sem I Sem II Sem. III Sem. IV Sem V Sem. VI

JPA and Hibernate IP OOPS with Python Core Java --- Project
C++
Persistence How it can be achieved in Java?
 Most business applications require that data must be persistent. Data can be labeled as
persistent only when it manages to survive day to day problems such as system crashes and
network failures.
 Often multiple users request from data simultaneously. Here, there is a definite possibility of
data getting corrupt, if mid-request, system failure, occurs. Maintaining the persistence of data
in an enterprise wide applications is quite a challenging job.
 In enterprise application architecture, data persistence is implemented as:
1. Having data stored outside an application’s active memory, known as persistent data
store, typically a relational database or an object database or a flat file system.
2. Having a rollback system, where, in case of system failure, the state of the data is rolled
back to its last known valid state.
 Persistence is one of the fundamental concepts of application development. It allows DATA to
outlive the execution of an application that created it. It is one of the most vital piece of an
application without which all the data is simply lost.
 Majority of the applications use persistent data. For example, GUI applications need to store
user preferences across program invocations, Web applications track user movements and
orders over long periods of time.
 Often when choosing the persistent data store the following fundamental qualifiers are
considered:
1. The length of the time data must be persisted.
2. The volume of data.

 Application may consider an HTTP session when life of a piece of data is limited to the user’s
session. However, persistence over several sessions or several users require a larger data store.
 Large amounts of Data should not be stored in an HTTP session, instead a database should be
considered.
 The type of database that is chosen also plays an important influence on the architecture and
design.
 Persistence in Java usually means storing data in a relational database using SQL.
 In Java, persistence is achieved by storing data in a Relational Database Management System
[RDBMS]. SQL is used to get data in and out of the relational database.
 Java Database Connectivity [JDBC] – The Java API is used to connect to the RDBMS and fire the
SQL statements.
Current Persistence Standards In Java
The Java platform was always supported for managing persistence to relational databases.
it provides programming interfaces that in turn provide gateway to the relational databases.

There already exist the following options that allow the Java developers to store and
retrieve persistent data:

Serialization

Serialization allows transforming an object graph into a series of bytes, which can then be
sent over the network or stored in a file.

Serialization seems to be quite simple, but it has a few limitations:

 Unsuitable For Large Amount Of Data

It must store and retrieve the entire object graph at once. This makes it unsuitable for

dealing With large amounts of data.

 Lacks strict data integrity

Changes made to objects cannot be undone, if an error occurs while updating information.
This makes it unsuitable for applications that require strict data integrity.

 No Concurrent Access To Information

Multiple threads or programs cannot read and write the same serialized data concurrently
without conflicting with each other.

 No Querying Capability

It provides no query capabilities.

JDBC

JDBC overcomes a lot of limitations that serialization has such as:

 It can handle large amounts of data

 Ensures data integrity

 Supports concurrent access to information.

 Provides a sophisticated query language in SQL

Unfortunately, JDBC does not provide ease of use.

JDBC was not designed for storing objects. JDBC allows the Java programs to fully interact
with the database. However, this interaction is heavily reliant on SQL. It requires a
considerable amount of code spec that deals with taking tabular row and column data and
converting it back and forth into

objects.

EJB 2 Entity Beans

The Enterprise Edition of the Java platform introduced entity Enterprise JavaBeans [EIBs]

EJB 2.x entities are components that represent persistent information in a data store.

EJB 2.x entities:

 Provide an object~oriented View of persistent data

 Use a strict standard, making them portable across vendors .

Unfortunately , EJB 2.x entities:

 They Are slow

 Are difficult to code

 Are not serializable

 Require a one-to-one mapping to database tables

 Require expensive application servers to run, as they have to reside within a J2EE
application server environment

 Require developers to determine which bean field maps to which table column

 Do not offer features such as inheritance, polymorphism and complex relations

Java Data Objects

Java Data Objects [JDO] was initiated to provide another persistence specification effort due
to the failures of the EJB persistence model.

JDO:

 Provides an object-oriented query language, which was not well accepted by the
relational database users.

 Unfortunately , EJB 2.x entities:Supports non-relational databases. In fact, it was


driven by members of the objed' oriented database community and is now being
adopted by object-oriented database products as the primary API

JDO never became an integrated part of the enterprise Java platform. It had many good
features in it and was adopted by a small community of devoted and loyal users who stuck
by it and tried to promote it.
Unfortunately the major commercial vendors did not share the same view of how a
persistence framework should be implemented.

Java Persistence API Introduction


https://www.youtube.com/watch?v=uilv3ZjidwQ

Need of Object Relational Mapping (ORM)


 There is a need of Object Relational mapping because it provides the following advantages.

 Better System Architecture.


 Most of the times all the application functionality and the database access code spec is
held together. This brings in some severe disadvantages.
 It becomes really difficult to reuse code spec. Hence code repetitions occur at several
different places. Changing anything becomes quite difficult, as each and every place that
holds the repetitive code spec needs to be located and changed accordingly.
 If the application functionality [business logic] and the database access code spec
[persistence mechanism] are separated, applying changes become very easy. Changes can
be made to one part without influencing the other parts.
 Reducing Coding Time.
 Most of the time the database access code spec is simple inserts, updates or deletes.
These are SQL statements which are quite tedious to code.
 ORM tools help here, by generating them on fly and thereby saves a lot of time.
 Caching And Transactions.
 Most ORM tools such as Hibernate comes with a feature such as Caching and
Transactions. These features if chosen to hand code are not so easy to implement. And it
definitely does not make sense to develop them when they already exist.

Introduction to Java Persistence API: The Java Persistence API

i. Java Persistence API is a specification, which is released under Java EE 5


specification.
ii. It is neither an implementation nor a product. Hence, it cannot be used as it is for
persistence. It needs an ORM implementation to work with and persist Java
Objects.
iii. Technically, JPA is just a set of interfaces [a Specification] and thus requires an
implementation.
iv. All specifications require vendors or open source projects to implement them.
Using JPA therefore requires picking up an implementation [ORM tool such as
Hibernate, Toplink, OpenJPA or any other ORM that implements JPA].
v. JPA defines the interface that an implementation has to implement.
vi. The whole point of having a standard interface is that users can, in principle,
switch between implementations of JPA without changing their code.
vii. This way, JPA helps prevent Vendor Lock-In by relying on a strict specification
such as JDO and EJB 2.x entities.
viii. Currently most of the persistence vendors[ORM tool providers] have released
implementations of JPA.
ix. Since, the Java Persistence code spec covers several persistence frameworks into
a single API, an application written using JPA will work across several
implementations [Hibernate, Toplink and so on].
x. This is very useful, especially when, development begins using the free open
source ORM implementations and later on when the need arises, the open source
implementation is swapped with a commercial ORM implementation. The switch
happens without changing the application code spec.

Object/Relational Mapping

1. Bridging the gap between the object model and the relational model is known as
Object-Relational Mapping
2. Object/Relational Mapping [ORM] is a technique that allows an application written in
an object oriented language to deal with the information as objects.
3. Rather than using database specific concepts such as ROWS, COLUMNS and
TABLES which is facilitated by a software called Object/Relational Mapper.
4. An Object/Relational Mapper is a piece of software that is used to transform:
 An OBJECT view of the data
INTO
 A RELATIONAL view
5. Object/Relational Mapper also offers persistence services
[CRUD] such as
CREATE
READ
UPDATE
DELETE
6. O/R mapping is performed by a persistence framework.
This framework knows how to:
 Query the database to retrieve objects
 Persist those objects back to their representation in the database’s tables and
columns

All this is known with the help of Mappings. Mappings are defined in metadata, typically
annotations.

What is an ORM
https://www.youtube.com/watch?v=LooPUh5_QKI
Persistence of Object Oriented Models.
Persistence in Java means storing data in a relational database using SQL.

It is accomplished by storing data in a Relational Database Management System [RDBMS].

Persistence of Object Oriented Models:


 Most of the development is carried out in an object oriented manner using
languages such as Smalltalk, C++ and Java.
 Object (Domain) modelling is a concept always linked with Persistence.
In fact, it is often the domain model that is persisted.
 Object Oriented Programming is based on OBJECTS that represent the business
model ie. the real world.
 Objects are easily traversed through relationship graphs using inheritence,
associations.
 In terms of Java, being the programming language of choice, the business logic of an
application works with Objects of different class types.
 Although, while dealing with the data store, it's important to note that the database
are not objects, which becomes an issue.
 Object Persistence deals with persistence in object oriented programs such as Java.
It means determining how objects and their relationships are persisted in a relational
database.
 Object Persistence is about:
- Mapping object state.
- Determining how an object's state [data stored in member variables of an object] is
stored in database table columns.
- Dealing with the fact that object state types may not align with relational database
types.
- Mapping object relationships.
- Determining how associations between objects are stored as relational database
keys or in relational database intersection tables.
Architecture of JPA
Persistence
javax.persistence.persistence contains static helper methods to obtain
EntityManagerFactory instances in a vendor-neutral fashion.
EntityManagerFactory

EntityManagerFactory is created With the help of a Persistence Unit during the


application start up. It serves as a factory for spawning EntityManager objects when
required.
Typically, it is created once [one EntityManagerFactory object per database] an
kept for later use. javax.persistence.EntityManagerFactory class is a factory for
EntityManagers.
EntityManager
Javax.persistence.EntityManager is lightweight and inexpensive to create. It provides
the main
Interface to perform actual database operations.
All the POIOs i.e. persistent objects are saved and retrieved With the help of an
EntityManager object.
Typically, EntityManager objects are created as needed and destroyed When not
required.
Each EntityManager manages a set of persistent objects and has APIs to insert new
objects and delete existing ones.
When used outside the container, there is a one-to-one relationship between an
EntityManager and an EntityTransaction.
EntityManagers also act as factories for Query instances and CriteriaQuery
instances.
Entity
Entites are persistent objects that represent datastore records.
EntityTransaction
A Transaction represents a unit of work with the database.
Any kind of modifications initiated via the EntityManager object are placed within a
transaction. An EntityManager object helps creating an EntityTransaction object.
Transaction objects are typically used for a short time and are closed by either
committing or rejecting.
Query
Persistent objects are retrieved using a Query Object.
Javax.persistence.Query allows using SQL or Java Persistence Query Language [JPQL]
queries to retrieve the actual data from the database and create objects.
Multiple Query instances can be obtained using an EntityManager.

Criteria
Criteria API is a non-string-based API for the dynamic construction of object-based
queries [javax.persistence.criteria].
Just like JPQL static and dynamic queries, criteria query objects are passed to
EntityManager.createQuery() to create Query objects and then executed using the
methods of the Query API.
A CriteriaQuery object can be thought of as a set of nodes corresponding to the
semantic
constructs of the query:
 Domain objects, which correspond to the range variables and other identification
variables of the JPQL FROM clause
 WHERE clause predicates, which comprise one or more conditional expression
objects
 SELECT clauses, which comprise one or more select item objects
 ORDER-BY and GROUP-BY items
 Subqueries
And so on...
How JPA Works?

1. An XML is created, or annotation are added to POJOs, which inform the JPA provider
about:
 The classes needed to store the data
 How the classes are related to the tables and columns in the database

This way all the necessary information is provided to the JPA provider.

2. During the runtime, the JPA provider reads the XML and/or annotations and
dynamically builds Java classes to manage the translation between the database and
the Java objects.
3. An EntityManagerFactory is created from the compiled collection of mapping
metadata. It provides the mechanism for managing persistent classes and
EntityManager.
4. EntityManager provides the interface between the persistent data store and the
application. It wraps a JDBC connection, which can be user managed or controlled by
the JPA provider and is only intended to be used by a single application thread, then
closed and discarded.
5. All the database interaction is done via a simple, intuitive API that JPA provides. This
API allows performing queries against the objects represented by the database. This
API informs the JPA provider:
 To save the changes whenever the objects are changed
 To store the objects in the database whenever new objects are created

JPA Specifications.

1. JPA 2.1
2. Stored Procedures
3. Unsynchronized Persistence Context
4. Schema Generation
5. Bulk Updates and Deletes using Criteria
6. Function in JPQL
7. Downcasting in JPQL
8. JOIN condition using ON
9. Entity Listener using CDI
10. Dynamically defined Named Queries

Some of them are explained below:


 JOIN condition using ON
 The ON clause in SQL is used to specify the relationship between the tables. It is
different from the WHERE clause, which specifies the criteria for the records to be
picked.
 Join condition used for a join comes from the mapping’s join columns, which means
that the JPQL user is normally free from having to know how every relationship is
joined.
 In some cases it is desirable to append additional conditions to join conditions,
normally in the case of outer joins. This can be done through the ON clause.
 Example :
SELECT s.Name,COUNT(p)
FROM Suppliers s LEFT JOIN s.Products p
ON p.Status = ‘InSTock’
GROUP BY s.Name

The mapped SQL would be:


SELECT s.Name, COUNT(p.ProductNo)
FROM Suppliers s LEFT JOIN Products p
ON s.SupplierNo = p.SupplierNo AND p.Status = ‘InStock’
GROUP BY s.Name

 Explanation
o s.SupplierNo = p.SupplierNo condition is generated because of the LEFT JOIN.
o The additional JOIN condition p.Status = ‘InStock’ is also added to the
generated SQL because of the ON clause in the JPQL.
o The result of this query will include all suppliers with possibly NULL values.
o This is different from the query below:
SELECT s.Name, COUNT(p)
FROM Suppliers s LEFT JOIN s.Products p
WHERE p.Status=’InStock’
GROUP BY s.Name

 Entity Listeners using CDI


 Entity listeners allows handling cross-cutting lifecycle events in a non-persistent
listener class.
 In JPA 2.1, entity listeners support dependency injection through CDI.
 The usual lifecycle callback methods of @PrePersist, @PostPersist, @PreUpdate and
@PreRemove can be used from entities.
 The entity listeners can also be annotated with @PostConstruct and @PreDestroy for
their own lifecycle.
 Example:
Solution: [Customers.java]

1. @Entity
2. @EntityListeners(LastLogin.class)
3. Public class Customers {
4. @Id
5. private Integer customerNo;
6. private String firstName;
7. ….
8. }
Solution: [Listener: LastLogin.java]
1. public class LastLogin {
2. @PostPersist
3. public void lastLogin(Customers customer){
4. ……
5. }
6. }

Stored Procedures

i. JPA 2.1 added support for the invocation of predefined database functions and user-
defined database functions to the Java Persistence query language.
ii. @NamedStoredProcedureQuery specifies and names a stored procedure, its parameters
and its result type.
iii. This annotation can be specified on an entity or mapped superclass.
iv. The name specified in the annotation is then used in
EntityManager.createNamedStoredProcedureQuery().
v. The IN, OUT, and INOUT parameters can be set and used to retrieve values passed back
from the procedure. vi.
Example:
Defining the Stored Procedure using @NamedStoredProcedureQuery:

@Entity
@NamedStoredProcedureQuery(name="CustomerStoredProcedure",
procedureName="Purchase")
public class Product {
...
}

Registering the parameters for the stored procedure:


StoredProcedureQuery query =
EntityManager.createNamedStoredProcedureQuery("CustomerStoredProcedure");
query.registerStoredProcedureParameter(1, String.class, ParameterMode.INOUT);
query.setParameter(1, "Sharanam Shah");
query.registerStoredProcedureParameter(2, String.class, ParameterMode.IN);
query.setParameter(2, "Laptop");
query.execute();
String response = query.getOutputParameterValue(1);

Unsynchronised Persistence Context:


i. In JPA, by default, the persistence context is synchronised with the underlying resource
manager, which means that any updates made to the persistence context are propagated
to the resource manager.

ii. Unsynchronised persistence context allows an application to control the binding of the
CMP context to the current transaction.

iii. It also allows modeling JPA conversations ie. tracking persistent changes, but commit
them only at end of conversation, not each transaction.

iv. Basically an unsynchronised persistence context works by propagating the context within
the JTA transaction but not flushing the changes to the database, until
EntityManager.joinTransaction() is invoked.

v. Example:

@Stateful
public class ShoppingCart {

@PersistenceContext( type=EXTENDED,
synchronization=UNSYNCHRONIZED)EntityManager em;
Customer customer;
Transactions transaction;

public void startToShop(Integer customerNo) {


customer = em.find(Customer.class, customerNo);
transaction = new Transactions();
}

public void addToCart(Book book) {


Item item = new Item(book);
transaction.addItem(item);
}
public void confirmOrder() {
em.join Transaction()
customer.addOrder(transaction);
}

Schema Generation

Till now the developer used some provider specific features to generate the DB schema
from the Java classes.

Example:

Hibernate is used to automatically provide schema creation by using the following property;

1 <properties>

2<property name="hbm2ddl.auto" value="create"/>

3 </properties>

The above example, lacks some features such as foreign key generation, is not portable
through other JPA providers and generally lacks of DB creation optimizations.

Therefore, it is applicable in some simple use cases such as prototypes using b simple DBs
like HDB.

JPA 2.1 schema generation can be achieved be using using a richer set of annotations and
using some standard Properties.

Example:

Solution: [Using Properties]

1 <properties>

2<property name="javax.persistence.schema-generation-action" value="create"/>

3 <property name="javax.persistence.schema-generation-target" value="database"/>

4 </properties>

In order to achieve DB mapping of Java classes, the following standards should be followed:

 Table name is defaulted from Entity name

 Unidirectional OneToMany defaults to join table mapping


Example

Solution: [Using @Index]

1@Table(indexes={@Index(columnList=“FIRSTNAME“)

2 @Index(columnlist="CUSTOMERNO“)})

3 @Entity

4 pubic class Customers {

5 @Id

6 private integer customerNo ;

7 private String firstName;

8. ...

9 @ManyToOne

10 private Country country;

11 ...

12 }

Explanation:

@Index is used to specify additional indexes and the order of Indexes.

Solution: [Using @ForeignKeY]

1 @Entity

2 Public class Customers {

3 @Id

4 private Integer customerNo ;

5 private String firstName;

6 ...

7 @JoinColumn(foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY
(COUNTRYNO) REFERENCES COUNTRIES"))

8 private Countries country;

9 ...

10 }
Explanation:

@ForeignKey is used to specify foreign key constraint.

Be careful while using @ForeignKey, as it overrides the persistence providefs default


foreign key.

Bulk Updates

Criteria is an API for creating typesafe and / or dynamic Java Persistence queries.

In the previous version of IPA, support for updates and deletes was not available using
Criteria API.

In JPA 2.1, through the additions of CriteriaUpdate and CriteriaDelete classes, Support for
bulk updates and deletes is possible.

Example:

The following is the example of CriteriaUpdate, which allows a minimal salary of 10000 ta
every employee.

Solution:

CriteriaUpdate<Employees> updateEmployee =

cb.createCriteriaUpdate(Employees.class) ;

Root<Emloyees>employee==updateEmployee.from(Employees.class);
updateEmployee.set(employee.get(Employees.Salary),
10000).where(employee.lt(employee.get(Employees.salary), 10000));

Equivalent JPQL:

UPDATE Empioyees e SET e.Saiary = 10000 WHERE e.Salary < 10000

Bulk Update executed as:

@PersistenceContext

EntityManager entityManager;

Query query = entityManager.createQuery(updateEmployee);

query.executeUpdate();

Deletes Using Criteria

The following is the example of CriteliaDelete , which allows deleting the customer who is
inactive and who has not made any transaction.
Solution:

CrietriaDelete<Customers>deleteCustomer=

cb.createCritetiaDelete(Customers.class);

Rooot<Customers> customer=deleteCustomer.from(Customer.class);

deleteCustomer.where(cb. equal(customer.get(Customers.Status),"Inactive"),

cb.isEmpty(customer. get(Customers .Transactions)));

Equivalent JPQL:

DELETE FROM Customers c WHERE c.status='Inactive' AND c.Transactions IS EMPTY

Bulk Deletes executed as:

@PersistenceContext

EntityManager entityManager;

Query query = entityManagert.createQuery(deleteCustomer);

query.executeUpdate();

Develop a simple Inventory Application Using JPA.

Step 1 : Create a Web application name INVJPA

Step 2: Create database name Inventory  Table name Inventory

Create table Inventory(

itemId int Primary Key auto_increment,

itemName varchar(50),

description varchar(100),

quantity int,

addedDate varchar(50)

);

Step 3 : Add mysql connector in the library folder.

Step 4: Create a java class name as Inventory


package myApp;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Inventory")

public class Inventory {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name= "itemid", unique = true,updatable = false)
private Integer itemid;

@Column(name = "itemName")
private String itemName;

@Column(name = "description")
private String description;

@Column(name = "quantity")
private Integer quantity;

@Column(name = "addedDate")
private String addedDate;

public Integer getItemid() {


return itemid;
}

public void setItemid(Integer itemid) {


this.itemid = itemid;
}

public String getItemName() {


return itemName;
}

public void setItemName(String itemName) {


this.itemName = itemName;
}

public String getDescription() {


return description;
}

public void setDescription(String description) {


this.description = description;
}

public Integer getQuantity() {


return quantity;
}

public void setQuantity(Integer quantity) {


this.quantity = quantity;
}

public String getAddedDate() {


return addedDate;
}

public void setAddedDate(String addedDate) {


this.addedDate = addedDate;
}

Step 5: Create a persistence.xml file

Right click on your project  New  other  Select Persistence from the categories
 seclect Persistence Unit from files.
Let the name of Persistence be as it is. Select New Data Source 

Give JNDI name as : jdbc/Inventory

Database Connection as : New Database Connection

Next Select Driver: MySQL (Connector/J)

Click on Next  give the password as tiger  Finish

Check mark on Use Java Transaction  Table Generation Strategy : Select Create 
Click Ok

Step 6: Create index.jsp page

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="checkInventory.jsp" method="POST">
<table border="1">
<tr >
<td colspan="2" align="center"><b>Add the item in Inventory</b></td>
</tr>
<tr>
<td> Item Name</td>
<td><input name="itemname" maxlength="25" size="50" /></td>
</tr>
<tr>
<td>Description</td>
<td> <textarea rows="5" cols="36" name="description"></textarea></td>
</tr>
<tr>
<td>Quantity</td>
<td><input name="quantity" maxlength="4" size="5"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="AddToInventory"
value="AddToInventory"/></td>
</tr>
</table>
</form>
</body>
</html>

Step 7: Create checkInventory.jsp page

<%@page import="java.util.Iterator"%>
<%@page import="myApp.Inventory"%>
<%@page import="javax.persistence.EntityManager"%>
<%@page import="javax.persistence.Persistence"%>
<%@page import="myApp.Inventory"%>
<%@page import="javax.persistence.EntityTransaction"%>
<%@page import="java.util.List"%>
<%@page import="javax.persistence.EntityManagerFactory"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
private EntityManagerFactory eMF;
private EntityManager eM;
private EntityTransaction eT;
List<Inventory> inv;

%>
<%
eMF=Persistence.createEntityManagerFactory("INVJPAPU");

eM=eMF.createEntityManager();

String submit=request.getParameter("AddToInventory");
if(submit!=null&&("AddToInventory").equals(submit)){
try{
String itemname=request.getParameter("itemname");
String description=request.getParameter("description");
int quantity=Integer.parseInt(request.getParameter("quantity"));
String addedDate=new java.util.Date().toString();
Inventory inv=new Inventory();
inv.setItemName(itemname);
inv.setDescription(description);
inv.setQuantity(quantity);
inv.setAddedDate(addedDate);
eT=eM.getTransaction();
eT.begin();
eM.persist(inv);
eT.commit();
}
catch(RuntimeException e)
{
if(eT!=null)
eT.rollback();
throw e;
}
response.sendRedirect("checkInventory.jsp");
}
try{
inv=eM.createQuery("Select i from Inventory i ").getResultList();
}
catch(RuntimeException e){
throw e;
}
eM.close();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

</head>
<body>
<table border="1">

<tr>
<td colspan="5" align="center">
<b> Click<a href="index.jsp"> here</a> to add items in the Inventory </b>
</td>
</tr>
<tr>
<td>Item No</td>
<td>Item Name</td>
<td>Description</td>
<td>Quantity</td>
<td>Added Date & Time</td>
</tr>
<%
Iterator iterator= inv.iterator();
while(iterator.hasNext()){
Inventory objInv= (Inventory)iterator.next();
%>
<tr>
<td><b> <%= objInv.getItemid() %></b></td>
<td><b> <%= objInv.getItemName() %></b></td>
<td><b> <%= objInv.getDescription() %></b></td>
<td><b> <%= objInv.getQuantity() %></b></td>
<td><b> <%= objInv.getAddedDate() %></b></td>
</tr>
<%
}
%>
</table>
</body>
</html>

 Introduction to Hibernate: What is Hibernate?

Hibernate:
Hibernate is the latest Open Source persistence technology. It is available as a free open
source ORM library for the Java programming language.
It provides a framework for mapping an object oriented domain model to a traditional
Relational Database.
Hibernate was developed by a team of Java software developers around the world, with a
goal to relieve the developers from 95% of commom data persistence related
programmimg tasks by:
-Making the developer feel as if the database contains plain Java objects, without having
them worry about how to get them out of [or back into] database tables.
-Allowing the developers to focus on the objects and features of the application, without
having to worry about how to store them or find them later.
Its primary feature is mapping from:
- Java Classes --> Database Tables
- Java Data Types --> SQL Data Types
Also, hibernate allows querying and retrieving data. It generates all the necessary SQL calls
to achieve this and thereby, relieves the developers from manual result set handling and
object conversion.
In order to use Hibernate, JavaBean classes that represents the table in the database have
to be created. Also, the instance variables of the class are mapped to the columns in the
database.

Reasons behind using Hibernate:

 Hibernate can be used to develop/package and distribute the applications for free.
 It eliminates the need for repetitive SQL.
 It allows working with classes and objects instead of queries and result sets which
makes the approach more Object Oriented and less procedural.
 Handles all Create, Read, Update, Delete[CRUD] operations.
 Brings in portability across databases.
 Supports IDEs such as Eclipse, NetBeans by providing a suite of plug-ins.
 Reduces the development time by supporting inheritence, polymorphism,
composition and the Java Collection framework.
 Supports connection pooling.
 Supports wide range of database such as:
- Oracle
- MySQL
- MS SQL Server
- Interbase
- Pointbase
- Frontbase , and much more.
Hibernate Tutorial Part 1 - Introduction to Hibernate ( Concept)
https://www.youtube.com/watch?v=onS9G0zpQwA

Components of Hibernate

Hibernate is made up of the following three components:

Connection Management

Hibernate's Connection management service provides efficient management of the


database connections. Database connection is the most expense portion of an application
that allows interacting with the database.

Transaction Management

Transaction management service provides the ability to execute more than one database
statements at a time.
Object Relational Mapping

Object relational mapping is a technique of mapping the data representation from an


object model to a relational data model. This part of Hibernate is used to SELECT,
INSERT,UPDATE and DELETE records from the underlying database tables.

Usually a populated object of a POJO is passed to Session.save(). Hibernate reads the state
of the Variables of that object and executes the necessary SQL query.

Architecture of Hibernate

Configuration

The Configuration object represents a configuration or properties file for Hibernate. It is


usually created once during application initialization.

The Configuration object reads the properties [hibernate.properties/hibernate.cfg.xml] to


establish a database connection. Typically, a Configuration object is spawned to create a
SessionFactory.

Session Factory

SessionFactory is created with the help of a Configuration object during the application
start up. It serves as a factory for spawning Session objects when required.
Typically, it is created once [one SessionFactory object per database] and kept alive for later
use.

However, for application that require interacting with multiple database, multiple
SessionFactory objects [ each with a separate configuration object.]

Session

Session objects are lightweight and inexpensive to create. They provide the main interface
to perform actual database operation.

All the POJOs i.e. persistent objects are saved and retrieved with the help of a session
object.

Typically, session objects are created as needed and destroyed when not required.

Transaction

A transaction represents a unit of work with the database.

Any kind of modification initiated via the session object are placed with in a transaction. A
session object helps creating a transaction object.

Transaction object are typically used for a short time and are closed by either committing or
rejecting.

Query

Persistent objects are retrieved using a query object.

Query objects allows using SQL or Hibernate Query Language [HQL] queries to retrieve the
actual data from the database and create objects.

Criteria

Persistent objects can also be retrieved using the criteria object.

Criteria uses an object/ method-based means of constructing and executing a request to


retrieve objects.

All the configuration files created in hibernate applications


(hibernate.cfg.xml, hibernate.reveng.xml )
i. Hibernate uses hibernate.cfg.xml to create the connection and setup the required
ii. The file is used to provide the information which is necessary for making database
connections.
iii. hibernate.cfg.xml defines information such as the database connection and resource
mappings.
Steps to create configuration files in hibernate applications:
1. Right-click the Source Packages folder. Select New --> Other..
New File dialog appears. Select Hibernate from the Categories list and select Hibernate
Configuration Wizard from the File types.
2. Click Next. By default the file name is entered as hibernate.cfg in the File Name textbox.
3. Click Next. Select Data Source section of the Hibernate Configuration Wizard appears.
4. Select the option New Database Connection.. from the Database Connection drop down
list box.
5. New Connection Wizard dialog box appears. Select MySQL(Connector/J driver) option
from the Driver drop down list box.
6. Click Next. Customize Connection section of the New Connectiion Wizard dialog box
appears. Populate the fields according to the database requirements.
7. Click Finish. Select Data Source section of the Hibernate Configuration Wizard appears.
Fill the Database Connection and the Database Dialet details.
8. Click Finish.

How Hibernate works?


 An XML mapping document is created, which informs Hibernate about:
 The classes need to store data
 How the classes are related to the tables and columns in the database
 The mapping document is compiled, when the application starts up. It provides the
Hibernate framework with all the necessary information.
 During the runtime, Hibernate reads the XML mapping document and the
dynamically builds Java classes to manage the translation between the databases
and the java objects.
 SessionFactory is created from the compiled collection of mapping documents.
SessionFactory provides the mechanism for managing persistent classes and the
Session interface.
 Session provides the interface between the persisted data store and the
application. Session wraps a JDBC connection, which can be user managed or
controlled by Hibernate and is only intended to be used by a single application
thread, then closed and discarded.
 All the database interaction is done via a simple, intuitive API that Hibernate
provides. This API allows performing queries against the object represented by the
database. This API informs Hibernate :
 To save the changes whenever the objects are changed.
 To store the objects in the database whenever new objects are created.
Example

Develop a Hibernate application to store Feedback of Website visitor in MySQL database.

Hibernate – Feedback of Website Visitor (on index paper)

Step 1: Create MySql Database

Create table guestbook (no int primary key auto_increment, name varchar(20), msg
varchar(100), dt varchar(40));

Step 2: Create a Hibernate Project :-


File -> New Project -> Java Web -> Web application - > Next -> give the project name ->
browse the location as required -> select the checkbox – “dedicated folder for storing
libraries” -> Next
Select glassfish server -> next
Select frame work - hibernate -> select the respective database connection -> finish.

Step 3: Adding Reverse Engineering File :-

Right click on Project -> new -> other -> select Hibernate -> Hibernate Reverse Engineering
wizard file type -> next -> file name (hibernate.reveng) , folder -> click on browse and
select src->java -> next -> select guestbook table name from the available tables option ->
click add ( select the checkbox – include related files) -> finish.

Step 4: Adding Hibernate mapping files and POJOs from Database file type:-

Right click on Project -> new -> other -> select Hibernate -> Hibernate mapping files and
POJOs from Database file type) -> next -> keep the default configuration file name file name
(hibernate.cfg) and Hibernate Reverse Engineering File (hibernate.reveng) -> type the
package name (hibernate) -> finish.

Step 5: Creating JSP File :-


Right click on project -> new -> JSP -> filename -> guestbookview -> select radiobutton ->
JSP file (Standard syntax) -> Finish.

Program:-
File name - Guestbook.java
package hibernate;
public class Guestbook implements java.io.Serializable {
private Integer no;
private String name;
private String msg;
private String dt;

public Guestbook() {
}

public Guestbook(String name, String msg, String dt) {


this.name = name;
this.msg = msg;
this.dt = dt;
}

public Integer getNo() {


return this.no;
}

public void setNo(Integer no) {


this.no = no;
}
public String getName() {
return this.name;
}

public void setName(String name) {


this.name = name;
}
public String getMsg() {
return this.msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getDt() {
return this.dt;
}
public void setDt(String dt) {
this.dt = dt;
}
}

File name - hibernate.cfg.xml


<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:3306/db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">tiger</property>
<mapping resource="hibernate/Guestbook.hbm.xml"/>
</session-factory>
</hibernate-configuration>

File name - Guestbook.hbm.xml


<hibernate-mapping>
<class name="hibernate.Guestbook" table="guestbook" catalog="db">
<id name="no" type="java.lang.Integer">
<column name="no" />
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="name" length="20" />
</property>

<property name="msg" type="string">


<column name="msg" length="100" />
</property>

<property name="dt" type="string">


<column name="dt" length="40" />
</property>

</class>
</hibernate-mapping>

File name - index.jsp


<html>
<head>
<title>Guest Book</title>
</head>
<body>
Guest Book <hr><br><br>
<form action="guestbookview.jsp" >
Name <input type="text" name="name" maxlength="20"><br>
Message <textarea rows="5" cols="40" maxlength="100" name="msg"></textarea>
<br><input type="submit" value="submit">
</form>
</body>
</html>

File name - guestbookview.jsp


<%@page import="org.hibernate.SessionFactory"%>
<%@page import="org.hibernate.Session"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@page import="org.hibernate.Transaction"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Iterator"%>
<%@page import="hibernate.Guestbook"%>

<%!
SessionFactory sf;
org.hibernate.Session ss;
List<hibernate.Guestbook> gbook;
%>

<%
sf = new Configuration().configure().buildSessionFactory();
ss= sf.openSession();
Transaction tx=null;
Guestbook gb=new Guestbook();
try
{
tx=ss.beginTransaction();
String name=request.getParameter("name");
String msg=request.getParameter("msg");
String dt=new java.util.Date().toString();
gb.setName(name);
gb.setMsg(msg);
gb.setDt(dt);
ss.save(gb);
tx.commit();
}
catch(Exception e){ out.println("Error"+e.getMessage()); }
try
{
ss.beginTransaction();
gbook=ss.createQuery("from Guestbook").list();
}
catch(Exception e){ }

%>

<html>
<head>
<title>Guest View</title>
</head>
<body>
Guest View
Click here to go <a href="index.jsp"> BACK </a>
<br><br>
<%
Iterator it=gbook.iterator();
while(it.hasNext())
{
Guestbook eachrecord=(Guestbook)it.next();
out.print(eachrecord.getDt()+" ");
out.print(eachrecord.getName()+"<br>");
out.print(eachrecord.getMsg()+"<br><hr>");
}
%>
</body>
</html>
Answer in Brief:

1. What is Persistence? How it can be achieved in Java?


2. Write a Short note on Persistence of Object Oriented Models.
3. What are the Persistence Standards available currently in Java.
4. Write a Short note on Object/Relational Mapping.
5. Why there is need of Object Relational Mapping(ORM)?
6. Explain Java Persistence API with specification.
7. Explain the architecture of JPA in detail.
8. How JPA works?
9. What are different JPA specifications? Explain any two in detail.
10. Write a short note on Stored Procedures and Unsynchronised Persistence Context.
11. Explain Schema Generation and Bulk Updates , Deletes using Criteria.
12. Write a short note on Functions in JPQL and Downloading in JPQL.
13. Explain the following
a. JOIN condition using ON
b. Entity Listeners using CDI
14. What is Hibernate ? State the reasons behind using Hibernate.
15. Explain the components of Hibernate.
16. Explain the architecture of Hibernate.
17. How Hibernate works?
18. Explain all the configuration files created in hibernate applications.
(hibernate.cfg.xml, hibernate.reveng.xml)

You might also like