EJ Unit 5
EJ Unit 5
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:
Recommended Books
Books:
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.
It must store and retrieve the entire object graph at once. This makes it unsuitable for
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.
Multiple threads or programs cannot read and write the same serialized data concurrently
without conflicting with each other.
No Querying Capability
JDBC
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.
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.
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
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.
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.
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.
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
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
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 {
...
}
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;
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>
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:
1 <properties>
4 </properties>
In order to achieve DB mapping of Java classes, the following standards should be followed:
1@Table(indexes={@Index(columnList=“FIRSTNAME“)
2 @Index(columnlist="CUSTOMERNO“)})
3 @Entity
5 @Id
8. ...
9 @ManyToOne
11 ...
12 }
Explanation:
1 @Entity
3 @Id
6 ...
7 @JoinColumn(foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY
(COUNTRYNO) REFERENCES COUNTRIES"))
9 ...
10 }
Explanation:
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:
@PersistenceContext
EntityManager entityManager;
query.executeUpdate();
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"),
Equivalent JPQL:
@PersistenceContext
EntityManager entityManager;
query.executeUpdate();
itemName varchar(50),
description varchar(100),
quantity int,
addedDate varchar(50)
);
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")
@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;
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
Check mark on Use Java Transaction Table Generation Strategy : Select Create
Click Ok
<%@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>
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.
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
Connection Management
Transaction Management
Transaction management service provides the ability to execute more than one database
statements at a time.
Object Relational Mapping
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
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
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
Query objects allows using SQL or Hibernate Query Language [HQL] queries to retrieve the
actual data from the database and create objects.
Criteria
Create table guestbook (no int primary key auto_increment, name varchar(20), msg
varchar(100), dt varchar(40));
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.
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() {
}
</class>
</hibernate-mapping>
<%!
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: