Hibernate (Part I)
Hibernate (Part I)
Hibernate (Part I)
Insert, update, delete and select operations on persistent stores to manipulate data are called
persistence operations. These operations are also called a CURD or CRUD or SCUD operations.
CURD:
C Create (insert)
U Update
R Read (Select)
D Delete
CRUD:
C Create (insert)
R Read (Select)
U Update
D Delete
SCUD:
S Select
CCreate
U Update
D Delete
Logic written in software application to interact with persistent store and perform persistent
operations is called persistence logic.
EX: JDBC Code, Hibernate Code, I/O Stream Code and e.t.c.,
Presentation Logic: The logic that generates user interface for end user is called presentation
logic. End user uses this user interface to supply inputs to application and to view results given
by application. (OR)
1
To view formatted results given by application. The main logic of application that generates
results based on given inputs is called business logic.
Sample Application: Read sno, sname and marks from end user (Persistence logic) calculate
total and average.
tot=m1+m2+m3
Generate rank for the student based his marks avg*(business logic)
Note: If there is no separate business logic then persistent logic itself acts business logic of
application.
Files are good as persistent stores only in small scale applications like desktop games, mobile
games e.t.c., but there are not good as persistent stores in large scale projects. Database softwares
are good as persistent stores in medium, large scale organizations. EX: Banking websites e.t.c.,
Limitations of Files:
1. No security
2. No query language support
3. Update and delete operations are complex.
4. Manipulating data with multiple conditions is complex.
5. Merging and comparison.
Object Database Software: The Database software which can store software object as Database
table column value is called Object Database Software.
2
{
-------------
---------------
m1=30
m2=50
m3=70
11 Bhargav
12 Reddy
i. They store multiple values in the single Database table column as software object but
storing multiple values in single Database table columns is against of normalization rule
number 1.
3
ii. Generating reports from the Database table of Object Database softwares is complex
process.
Java application can use either JDBC or o-r mapping concepts to develop JDBC mapping
concepts and to interact with Database softwares. In small scale organizations we use files as
persistent stores and use I/O Streams to develop the persistent logic.
Payroll applications
In Large scale organizations Database software used as persistent store and use or mapping
style persistent logic.
Drawbacks of JDBC:
1. SQL Queries are Database software dependent queries. JDBC uses SQL Queries so
JDBC persistent logic is Database software persistent.
2. Changing Database software in the middle of project development or production
environment is complex process.
3. All Exceptions in JDBC programming are checked exceptions we must catch and handle
those exceptions.
4. JDBC supplied Middleware services but those are not sufficient not good for industry
standard projects.
5. Middleware services are security transaction JDBC connection pooling and e.t.c., to
overcome all the above problems we use o-r mapping persistence logic instead of JDBC
persistence logic.
6. The Parameters of PreparedStatememnt related SQL query allows only positional
parameters (?) and they does not allow named parameters.
7. We can send only Serializable Java objects over the network. JDBC ResultSet object
can’t be sent over the network because it is not serializable object.
4
8. In JDBC programmer have to Write more common logics along with application
specific logics in every JDBC application (Scratch level coding is required).
A) The process of linking/mapping Java class with Database table, Java class member variables
with Database table columns and making objects of that Java class representing Database table
records having synchronization between them is called o-r mapping. If any modification done in
Java object it reflects in row/record of Database and vice-versa.
Here the word synchronization is not related to Multithreading. To develop o-r mapping
persistence logic there is no need of working with SQL queries we just need to work with Java
objects that are representing Database table records and we use these objects to perform all
persistent operations on the table (CURD Operations). This whole process makes or mapping
persistence logic as Database software independent persistence logic.
Ibatis Apache 4
------------
5
------------ Methods
---------------
Stno : 101
Stno : 102
Sname: Vijay
6
The ORM software like Hibernate takes the responsibility if maintaining synchronization
between Java objects and Database table records. The following are the o-r mapping(ORM)
softwares.
Hibernate Def: Hibernate is open source lightweight and Java based ORM software to develop
object based Database software independent o-r mapping persistence logic in Java, Jee and Java
Framework software based applications.
1. When hibernate software is installed it gives its source code to programmers and
moreover Hibernate is free software due to this we say Hibernate is opensource software.
2. EJB Components are heavy weight components because they need heavy weight
container, server softwares for execution.
3. The resources of EJB components are EJB API dependencies. Hibernate software and
Hibernate components are light weight because to execute Hibernate applications we use
just JDK software, Hibernate Software and there is no need of working with the heavy
weight containers, server softwares.
4. Some resources of Hibernate applications can be developed without using Hibernate API.
5. We can write Hibernate logic in any kind of Java applications to make them taking with
Database Software.
Framework: Framework is special software that is built on the top of core technologies having
the ability to generate the common logics of the applications dynamically while working with
Framework softwares.
1. Programmer just develops application specific logics because the Framework software
automatically generates the common logics of application dynamically by using core
technologies internally.
2. Framework software provides abstraction layer core technologies internally generate
some common logic but they never make programmer bothering or knowing about these
core technologies.
1,2,3,6,7 and 8 are common logics because they are always same in JDBC based Java
applications.
4,5 are application specific logics because they vary in each JDBC based application.
Here Hibernate software internally uses JDBC code and generates all the above discussed
common logics of persistence code. In Java environments three types of Framework
softwares. Those are
2. ORM Framework Softwares: These softwares provides abstraction layer on the core
JDBC technology. Simplifies the process of developing the persistence logic in o-r
mapping style.
3. Java-jee Framework softwares: These softwares provides abstraction layer of Java, Jee,
Core technologies, JDBC, RMI, JNDI, Servlets, JSP, JMS, Java mail, EJB e.t.c., allows
to develop all kinds of Java jee applications Framework style.
EX: Spring
Features of Hibernate:
8
4. Can be used along with Java, JEE, Java Framework software applications to make them
internally with ORM software.
5. Gives built in JDBC Connection pool also allows to work with third party supplied and
server managed JDBC Connection pool.
6. Gives built in transaction management support and also allow working with server
managed Transaction management.
Note: Hibernate gives built-in middleware service and also allowed to work with third party
or server supplied middleware services.
Note: Middleware services are additional and optional services which can be applied to our
application to make our application running smoothly in all sitchuations.
7. Gives the records of the table directly in the form of Collection Framework data
structures which are serializable objects by default.
8. Gives the Database software independent query language called HQL.
9. Also allows using direct SQL queries to develop persistence logic.
10. Throws only un checked exceptions so Exception Handling while developing Hibernate
persistence logic is optional.
Note: Even though Hibernate uses JDBC and even though JDBC code throws Checked
exceptions the Hibernate software converts them to unchecked exceptions by using
Exception Rethrowing concept.
try
-------------
Catch(SQLException se)
}
9
}
Note: Annotations are Java statements that are alternate for the XML file resources
configuration and other applications
14. Also supports JPA standards of o-r mapping persistence logic development.
Note: JPA defines set of rules and guidelines that are required to develop ORM softwares
due to this programmers can work with all these ORM Softwares in a common way.
Note: Buffering in Hibernate based client application reduces the network round trips
between client and server.
Application Database Software: When the Java class is taken as resource of Java
technology based software application and if that class not extending, not implementing pre
defined class and interface of that technology specific API then that Java class is called as
POJO Class.
EX: When Java class is taken as resource of Hibernate application and if that class not
extending, not implementing pre defined class or interface of Hibernate API then that class is
called as POJO Class.
EXAMPLES:
class Test
---------
----------
10
EX2:
-----------
------------
--------
EX3:
--------------
--------------
ABC is user defined class and not extending from other class.
EX4:
---------------
---------------
EX5:
11
{
------------
-------------
EX6:
-----------------
--------------------
Test is POJO class because serializable(I) is very much of Core programming concepts of
Java.
JDBC, JNDI, EJB, Servlets and JSP e.t.c., are called technologies
Java.lang, java.util, java.io and their sub packages are very much part of basic Java
programming .
EX:
--------------
-------------
Text is POJO.
EX:
12
{
-------------
-------------
EX:
Class Test
--------------
EX:
--------------
-------------
POJI: When Java interface is taken as resource of certain technology based Java application
and that interface is not extending from predefined interfaces of that technology specific API
then that interface is called POJI.
13
EX: When Java interface is taken as the resources of Hibernate application and that interface
is not extending from predefined interfaces of Hibernate API then that interface is called
POJI.
NOTE: The POJO and POJI model programming support that is there in Hibernate
programming makes the Hibernate applications as light weight applications.
Interface Demo
-----------------
------------------
“Demo” is POJI .
---------------
---------------
-----------------
-----------------
14
--------------------
---------------------
Demo1 is user defined interface not extending form other interfaces. So Demo is POJI.
------------------
---------------------
--------------
---------------
Hibernate 3.6 installation: If we install Hibernate 3.6 software download the following zip
file www.hibernate.org website.
Hibernate_distribution_3.6.5.Final_dist.zip
When we place Hibernate persistence logic in our applications then our applications
become client to Database software but not Client to Hibernate Software.
15
Java application(Clint to Database)
Hibrnate Code
Persistence
Loic
16
To develop Hibernate persistence logics we need to following main resources.
Using Hibernate we just develop persistence logic and it can’t be used to develop other
logics. So programmers always use Hibernate along with other technologies in project
development with respect to the diagram client application locates Hibernate resources.
ii) Client application develops object based o-r mapping persistence logic by using the
located Hibernate resources and Hibernate API.
iii) The persistence logics of Client application gives instruction to Database software.
1
Hibrnate cfg
Object based o-r N Database Software
file
mapping
persistence E
logic 2
T 4
Hibernate
Persistence Hibernate W
class(Java Bean) Mapping
File(XML) O
K
Java appl/AWT Swing App
---------------------------------------
17
iv) The Data in Database tables will be manipulated.
v) Client application receives results from Database software in the form of objects for o-r
mapping programming.
This file contains JDBC driver details, Database user name, Password details and also
other details instructions using which hibernate software can establish connection between
Java application and Database software.
This file carries all above said details as the values of fixed hibernate properties. This file
also contains the named location of hibernate mapping file. The following are minimum
entries hibernate properties of configuration file.
hibernate.dialet
The values of Hibrnate configuration file will change based on the JDBC driver, Database
software and its version be utilized. We can gather all property names of Configuration
file(nearly 60+) either from hibernate 3.6 home project/etc/hibernate properties file(or) from
hibernate 3.6 home/ documentation/manual en-us/pdf/ hibernate-reference.pdf file related
(Chapter 3)
A) The values specified in this property guides hibernate software in the following ways.
18
1) Assign intelligent and meaningful values: Names Hibernate software to assign
intelligence sensible and meaningful default values for those hibernate properties that are not
specified in configuration file. This saves the time of the programmer. More over hibernate
software generates default values based on Database software.
2) Generate Correct and needed SQL queries: Helps hibernate software to generate
correct and needed SQL queries internally while interacting with Database software. This
process is called optimized SQL query generation.
3) The Dialect Class is Hibernate Software supplied Java class and subclass of
org.hibrnate.dialect.Dialect
4) The class name changed based on Database software and its version be utilized.
Refer chapter3 of pdf file for mote other Databases related dialect classes.
Note: All the above dialect classes are sub classes of org.Hibernate.dialect. In Most of the
sitchuations Hibernate software automatically choose the dialect. So hibernate.dialect
property is optional. But configuration is recommended.
Hibernate Persistence Class: This class is Java bean class having POJO class behavior.
Objects of this class represent the records of the Database table.
1. Developers use this class while developing object based o-r mapping persistence logic.
Generally this class will be taken as one per Database table.
2. Objects of this class are really responsible to develop o-r mapping persistence logic. This
class is also called Hibernate POJO class or entity value class or value object class.
1. Any <filename>.xml can be taken as hibernate mapping file and this filename must be
mention is configuration file.
2. There is no default name for hibernate mapping file. This file contains various o-r
mapping configurations like basic o-r mapping component mapping, inheritance mapping
and e.t.c.,
19
3. Every mapping file contains basic o-r mapping configurations which are nothing but
mapping Java class with Database table, Java class member variable with Database table
columns and e.t.c.,
4. This file guides hibernate software towards generating the internal JDBC code. In one
application we can have one or more hibernate mapping files.
Client Application:
1. This can be any Java, J2EE application acting as client to Database software this
application activates hibernate software by locating and reading hibernate configuration
mapping files
2. This application uses Hibernate API and Hibernate POJO class (Persistence class objects)
to develop objects based o-r mapping persistence logic.
3. Client application uses this o-r mapping persistence logic to incorrect with Database
software and to perform CURD operations on Database tables.
Integration logic is responsible to monitor and control all the operations of the
applications execution. Combination of various technologies to develop MVC based
architecture projects
1. Servlet
2. Servlet Fileter
Struts, JDF, Web Framework, Spring MVC, Tapstrey, Cocoon, OAF(Oracle activation
Framework) and e.t.c.,
Hibernate, Ibatis, JDBC, OJB, TopLink, OJB, Open JPA, EJB Entiry bean, JDO e.t.c.,
The high-level architecture of the Struts, Spring and Hibernate based projects.
Presentation Layer
JSP, HTML
Control Layer
Action Servlet
Service Layer
Persistence Layer
Data Layer
Client applications of Hibernate maintain HB POJO class object (Hibernate persistence class
object) in three states.
i) Transient State
ii) Persistent State
iii) Detached State
The logical memory in client application where all persistent state objects are there is
called as persistence context.
21
i) Transient State:
1. Does not contain identity value.
2. Does not represent Database table.
3. This state will be there for HB Pojo class object before entering persistence context.
4. When programmer creates explicit object for HB POJO class its default state is transient.
ii) Persistence State:
1. Resides inside the persistence context contains identity value represent Database table
records having synchronization.
2. In Hibernate programming the total or mapping persistence logic will be written based on
this state objet.
iii) Detached State:
1. When persistence context is closed or Database software is down or Database table
records is deleted then persistence state object of persistence context becomes detached
state object.
2. This object contains identity value but does not represent Database table record while
developing persistence logic of hibernate in our client applications we need to write two
important objects. Those are
a) Hibernate SessionFactory Object
b) Hibernate SessionObject.
22
Understanding SessionFactory and Sessionstate object:
Configuration class
Hibernate creates
Object
SessionFactory
object
con con
Persistence
Hibernate Session object
context
No:101
rep
Name:Siva Stu.db
The HTTP session object of servlets and JSP programming is no way related with Hibernate
SessionFactory, Session object. When client application creates org.hibernate.cfg configuration
then the Hibernate software will be activated when client application calls close() on
SessionFactory object. Then the hibernate software will be deactivated configuration class object
is required to create SessionFactory object and this SessionFactory object is required to create
hibernate session object.
23
Q) What is the use of Hibernate SessionFactory, Session Objects? What is the difference
between SessionFactory and Hibernate Session objects.
Session Factory: It will be created based on the entries of Hibernate configuration file by using
org.hibernate.cfg.Configuration class object.
1. This object is generally on one per Database represents JDBC Connection pool that is
there in Hibernate software based Hibernate Configuration file entries. This object also
represents other resources like caches
2. SessionFactory object is the object of Java class that implements
org.hibernate.SessionFactory(I).
3. This object is capable of creating one or more Hibernate session objects
Hibernate Session object: The SessionFactory object takes one JDBC connection object from
its JDBC Connection pool and gets one JDBC statement object based on that connection object
and also creates Hibernate Session object by encapsulating JDBC Connection, Statement objects.
1. In One application there can be one or more Hibernate Session objects. Hibernate
Session object represent persistence context. Hibernate Session Object provides API
and environment to develop object based o-r mapping persistence logic.
2. Each Hibernate Session object represents Connectivity with Database software.
3. It is mediator between Java application and Hibernate Software. That means Java
application gives instruction to Hibernate software using this Session object.
Immutable: Immutable object mans modification done in the data of the objects won’t reflect in
current object but will be reflected in newly created object.java.lang.String class object
Mutable: if modifications done in the current object itself then it is called Mutable Object.
All user defined Java classes and majority of predefined classes are gives as mutable classes.
String s=”hello”
s=s.contact(“how”) hello
String class
obj
24 Hello how
String buffer sb=new StringBuffer(“hello”);
String class
obj
hb
Hello how
Sb=sb.concat(“how”);
Hibrenate SessionFactory objects are immutable, Hiberate Session objects are immutable,
Session objects are mutable.
//build SessionFactory uses the hibernate configuration file entries of “cfg” object and creates
one JDBC connection pool and also creates and returns Hibernate SessionFactory object
representing that connection pool.
Session res=factory.openSession()
Open Session(): Makes SessionFactory object to create one Session object and this Session
object represent an empty persistent context by default. Since we activate hibernate software in
any environment by just creating object for configuration class(Predefiend). So we can say
Hibernate is light weight software.
25
Persistence operations in Hibernate
update(-)
delete(-)
load(-)
get(-,-)
save or update(-)
get(-,-)
merge(-)
and etc.,
P) Write a Hibernate application to insert record into Database table by using object based
o-r mapping persistence logic.
//hibernate.cfg.xml
26
<!DOCTYPE hibernate-configuration PUBLIC
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl
</property>
<property
name="hibernate.connection.username">scott
</property>
<property
name="hibernate.connection.password">tiger
</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect
</property>
27
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Hibernate persistence class must be Java Bean is a Java class that contains getter and setter
methods. Getter methods are there read data from Bean properties and Setter methods are there
to write data to bean properties.
Mapping File:
//employee.hbm.xml
<?xml version="1.0"?>
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
</class>
</hibernate-mapping>
//Employee.java
28
//declare Bean Properties
this.eid=eid;
return eid;
this.fname=fname;
return fname;
this.lname=lname;
29
}
return lname;
this.email=email;
return email;
//TestClient.java
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
30
//Activate Hibernate Software
cfg=cfg.configure("/hibernate.cfg.xml");
SessionFactory factory=cfg.buildSessionFactory();
Session ses=factory.openSession();
eb.setEid(101);
eb.setFname("rakesh");
eb.setLname("rao");
eb.setEmail("123422");
Transaction tx=ses.beginTransaction();
ses.save(eb);
tx.commit();
ses.close();
factory.close();
31
}
//OUTPUT:
C:\hbprograms\Demo1>javac *.java
C:\hbprograms\Demo1>java TestClient
s.
1. Hibernate3.jar
2. Antlr 2.7.6 jar
3. Commons-collectioons3.1 jar
4. Dom4j – 1.6.1
5. Javaassist-3.12.OGA
6. Jta-1.1.jar
7. Slf-4j-api-1.6.1
8. Hibernate-jpa-2.0-api.1.0.0.Final.jar
9. Ojdbc14.jarfile
32
Add above jar files to the class path. Environemental variable to the ext folder fo <java
bean>\jre\lib\ext folder .
1)Mainjarfile(available in<hibernate-3.6>home
Compile all above java source files and execute client application
i) Keep Database table in Oracle Database software having primary key constraint based on
column.
ii) Gather certain details that is required to work Oracle thin Driver
While developing first application of Hibrnate we can use one of the following four ways to
make java tools recognizing hibernate API.
Q) What is the difference between working with class path and working with ext folder?
33
3. New command prompt should be open 3. Not required.
to recognize added values.
4. Points to original location of jar, 4. Needs another copy of jar files.
directories and uses them directly
Hibernate internally uses JDBC PreparedStatement object to send and execute generated SQL
queries in Database software to see this generated SQL query as log message window use show
SQL property. In hibernate configuration file as shown below.
Hibernate cfg.xml:
<hibernate-configuration>
<session-factory>
<Property name=”connection.driver-class”>
Oracle.jdbc.driver.OralceDriver
||
||
<mapping resource=”employee.hbm.xml”/>
</session-factory>
</hibernate-configuration>
TestClient.java:
Cfg=cfg.configure();
Makes the activated hibernate software taking hibernate.cfg.xml file of current directories as
default hibernate configuration file.
34
Configuration cfg=new Configuration;
Cfg=cfg.configure(“/mycfg.xml);
The activated software using mycfg.xml file of current directory as hibernate configuration file.
Makes application activate hibernate software based on the jar files that are added to classpath or
ext folder. But this activated software doesnot read the entries of the file.
Cfg=cfg.configure(mycfg.xml)
To read and verify hibernate configuration mapping file entries by using the xml parser.
DOM4J(Document object model for java). The values red from these xml files will be stored as
the data of cfg object(Configuration xml parser is a software application which can validate and
process xml documents)
Hibernate gives DOM4J as its SAX parser and Tomcat, web logic servers give SAX parser
its xml parser. Temporarily log messages not containing in 3.6.5 because bug is there.
SessionFactory cfg=cfg.buildSessionFactory()
Hibernate properties stored in the cfg object to creae JDBC Connection Pool and also returns
SessionFactory object representing that Connection pool.
Session ses=factory.openSession();
Makes Hibernate SessionFactory object to create and return Hibernae Session Object. This
Session object represents an empty persistence context.
factory.close():
35
a) When this method is called cleans up the Connection pool represented by SessionFactory
Object.
b) Closes other resources associated with SessionFactory object(Caches)
c) Deactivates the Hibernate Software.
Note: Client application activates Hibernate software by creating object for configuration class
and deactivates by calling factory.close()
1. Takes the transient state object and keeps in persistence context because of this “cb”
object becomes persistence state object.
2. Identify field cfg(no) done in mapping file the identity value will be generated for “eb”
obj.
3. Make Hibernate software to take “eb” obj data and to insert that data as record in
Database table.
4. Makes the software to keep that “eb” object and inserted record resides in Synchronizing.
Transaction tx=ses.beginTransaction();
Ses.persistent(eb);
Tx.commit();
Save() Persist()
1. Session.save() first generates the 1. Session.persist(-) also insert the record
identity value then inserts the record by generating identity value.
and also returns the generated identity
value.
2. Prototype of Session.save(-) is public 2. Prototype is public void persist(object
serializable(object obj) throws obj) throws HibernateException.
HibernateException.
Due to Exception Rethrowing all exceptions become unchecked exceptions. All the Hibernate
API methods like session.save() internally uses JDBC code and throws checked exceptions like
SQLException. But these Checked Exceptions will be rethrown as unchecked Exceptions form
the catch blocks in the form of Hibernate Exception.
36
public serializable save(object obj) throws HibernateException
---------------
----------------
Catch(SQLException se)
return idvalue;
Transaction tx=ses.beginTransaction();
System.out.println(“identity value=”+idval);
Performing update, delete, select, insert operations on the Database table records hibernate
gives little bit bad performance to work with JDBC technology. Because hibernate internally
using JDBC to talk with Database software. This problem is solved by using cathing fecility upto
certain extent.
NOTE:
1. IDE softwares are not framework softwares because IDEs are not software technologies
where as frameworks are software technologies.
2. IDE is a tool that simplifies the process of working with software technologies.
3. Framework is a high end software technology which uses low end software technologies
internally to develop the applications quickly.
4. We can use IDE to develop both core and Framework software based applications.
37
To update the record:
Transaction tx=ses.beginTransaction();
Ses.update(eb);
tx.commit();
Take eb having existing value in eid member variable and new values in other variables.
Transaction tx=ses,beginTransaction();
Ses.merge(eb);
tx.commit();
For Complete Program Please refer Hibernate execution \CURD\ merge(-) folder.
Prototypes:
Session.update(-) updates the record of the table but does not return persistent state object
representing that updated record. Where as merge(-) returns persistent state object representing
the inserted record or updated record of the table.
ses.update(eb);
EmpBean eb1=(EmpBean)ses.merge(eb);
38
Transaction tx=ses.beginTransaction();
ses.saveOrUpdate(eb);
tx.commit();
-----------------
Both methods are perform insert/update operations on the Database table record but
session.merge(-) returns persistent state object representing that record where as
session.saveOrUpdate(-) does not return that persistent state object.
ses.saveOrUpdate(eb);
EmpBean eb1=(EmpBean)ses.merge(eb);
eb.setEid(102);
Transaction tx=ses.beginTransaction();
ses.delete(eb);
tx.commit();
HB POJO class object or persistent object never deletes but the object which representing record
delete.
Note: POJO class objects are just actors they just play roles.
Hibernate POJO class objects are like actors representing Database table records and having the
capability to play or perform insert, delete, update, select operations on the Database table
records.
39
Delete(eb) is called eb.object will not be destroyed but the record represented by eb object in the
Database table will be deleted.
When the record represented by persistent state object got destroyed then the persistent state
object becomes detached state object. We can use single HB POJO class object to perform
multiple operations on the Database table record like one actor playing multiple roles.
eb.setNo(101);
eb.setName(“Siva”);
eb.setLname(“reddy”);
eb.setMail([email protected]);
JDBC Hibernate
1. Core technology for developing 1. Framework to develop persistence logic
persistence logic. 2. Develops object based persistence
2. Develops SQL queries based logic(or mapping).
persistence logic. 3. Persistence logic is Database software
3. Persistence logic is Database software independent.
dependent. 4. Given by SoftTree (Red Hat)
4. Given by SUN Microsystem. 5. Internally use JDBC.
5. Internally uses streams. 6. Talks with Database software by
6. Talk with Database software directly. generating JDBC code.
7. Suitable for medium scale applications. 7. Suitable for large scale applications.
8. Lazy loading not possible when we call 8. Does not support lazy loading.
session.
40
ses.load(eb,103);
System.out.println(eb.getEid());
***Note: After inserting records from Database software we have to give Commit command
compulsory.
In the above code load(-,-) selects the records from the table by using the given identity value
and stores that record in the given eb object. The process of converting simple value to wrapper
class object is called autoboxing and reverse is called auto unboxing (introduced from jdk1.5).
EmpBean eb=(EmpBean)ses.load(EmpBean.class,109);
***Note: But this method never works the records which are inserted from Oracle software
directly. That means we have to insert our records through Hibernate or JDBC and retrieve them.
In the above code load(-,-) selects the record form table based on given identity value, stores that
record by creating object of given HBPOJO class(EmpBean) and returns that object.
In a running Java applications we take float variable to hold float value, String object to hold
String value similarly we take the object of java.lang.class hold class name or interface name.
We can use class properly to generate object of java.lang.class to develop representing only class
or interface.length, class are two predefined properties of Java programming. The
session.load(class, id) expects java.lang.class object representing POJO class.
A) session.load(obj,id) selects the record from the table into given HBPOJOO class object
irrespective of whether that object/record is used in further part of the application(eagar loading)
Session.load(class, id) selects the record from the table and stores into the object(HB POJO
class object) only when application starts utilization of that object/record. This is called lazy
loading.
Note: Cooment System.out.println() while working with both load(-,-) related examples and
observe the difference in the select SQL query generation (for lazy loading, eagar loading
41
demonstration) session.load(obj,id) expects an empty HBPOJO class object and stores the
selected record into that object.
Session.load(class,id) expects HBPOJO class and it only creates object for HBPOJO class to
store selected record. In standalone, small scale application where multiple layers are not there
use session.load(obj,id) in medium scale applications where multiple layers are there like MVC2
architecture based web applications use session.load(class,id)
A) Both methods are perform eagar loading of record from Database table session.load(obj,id)
throws org.hibernate.Object NotFoundException when the record is not found to select where as
session.get(class, id) does not throw any exception if record is not found to select.
If Java method return type is java.lang.Object class then that method can return object of any
Java class as return value. If the Java method parameter type is java.lang.Object class then we
can call that method with any Java class object as argument value.
Note: java.lang.Object is the topmost class in the inheritance hierarchy of any Java class. While
developing Hibernate persistence logic we can perform select operations on Database table as
not transient operations.
42
By calling session.flush(-): We can make Hibernate software synchronizing changes done in the
persistent state HBPOJO class objects to Database table records.
Usage: For example we select two records or one record or any number of records at a time then
the records will display as usually. For example at the time of selecting records if we want to
save changes then we go for this method in the example we selected 103 and 109 records so then
output is
Here kir,kir2 are two mail ids. So we have to change these things so we use flush(-) at the ending
of ses.close().
EmpBean eb1=(EmpBean)ses.get(EmpBean.class,103);
eb.setEmail("gir");
eb1.setEmail("gir2");
ses.flush();
ses.close();
43
factory.close();
By using session.refresh(-) we can make Hibernate software reloading record into persistent
state object. This is nothing but performing synchronization from table row to persistent state
object.
EmpBean eb=(EmpBean)ses.get(EmpBean.class,109);
try
Thread.sleep(2000);
catch(InterruptedException ie)
System.err.println("hello");
ses.refresh(eb);
ses.close();
factory.close();
44
Version: SUN Microsyste(Oracle)
Default: 3306
Allows to create logical Databases and also gives default logical Database(mysql,test). Logical
Databases are logical particions installed Database softwares every logical Database can contain
tables, uses PL/SQL procedures and functions.
If multiple projects of company are using same Database software then that Database
software will be installed only once but multiple logical Databases will be created in that
software for multiple software for multiple projects one per projects basis Database
name=orcl,test etc.,
Logical Database3
4.x setup
C;\mysql\bin\bin\mysql\bin
45
After installing mysql 4.x software we need to activate that software by using
<Mysql_home>\winmysql
Right click on traffic signal(system tray area) showmemy.Inf setup tab view and modify
user, password values save modification yes reactive mysql software by using above
procedure.
Inserting values:
Note: Database name is orcl or test, Database software name is Mysql, Oralce.
Tab view and modify user, password values save modification yes right click activate
mysql software by using above password.
Step-1:
46
Insert into employee values:
In the above environment our Database software is mysql4.x our logical Database is myDb1.
Mechanism:Type-4
1. Use this url when application and mysql Database software resides in the same machine.
2. Use this url when application and mysql software resides in two different machines
Mysql-connector-java-3.0
NOTE: SQL yog is suitable for developing mysql without mysql knowledge.
47
Cfg.setProperty(“Connection.driver_class”,”oracle.jdbc.driver.OracleDriver”);
Cfg.setProperty(“hibernate.connection.url”,”jdbc:oracle:thin:@localhost:1521:orcl”)
-----------
--------
Cfg.addFile(“employee.hbm.xml”);
Session ses=factory.openSession();
Chaining:
Calling one method on the results of the another method in a class is called chaining.
Output is 9.
48
We can use this method chaining concept to create Hibernate session object by having single line
of code.
Note: The method which has void it is not possible to participate in method chaining.
Plug-in: Plug-in is a patch software or software application that can be used to enhance the
functionalities of existing software and software application. In Java environment plugins comes
as jar files. Plugins of IDE simplifies the process of working with software technologies.
Eclipse MyEclipse
1. Open source 1. Commercial
2. Does not provide builtin plugins to 2. Provide built in plugins and allows to
work with advanced technologies but add plugins externally.
allows to add plugins.
3. Suitable for small scale projects. 3. Suitable for large scale projects.
Note: Easy Eclipse, Eclipse Galilio and etc., are alternative for MyEclipse which are developed
based on Eclipse.
MyEclipse Details:
Reverse Engineering: To Generating POJO class mapping file based on Database table.
Algorithms: Hibernate software identify each HBPOJO class object through its identity value.
We can make Hibernate software working with different algorithms/strategies to generate these
49
identity values dynamically. Every algorithm is having one nick name and class name if no
algorithm is configured the default algorithm is “Assigned”
Assigned Algorithm: It is default algorithm if no other algorithm is specified this algorithm can
generate all types of identity values based on the type of algorithm works with all Database
softwares. This algorithm uses the values set to identity field variables as identity value.
This is default algorithm that means upto now we developed all algorithms by using this
one.
Increment algorithm: This algorithm uses maximum value+1 and generates identity values of
type long, short or int. This algorithm works with all Database softwares.
This algorithm does not consider the deleted record values while generating identity value.
Identity algorithm: This means it take deleted value consider but it is not suitable for oracle.
Only for mysql, DB2 etc.,…. This algorithm uses Maximum value+1 formula to generate
identity value of type int,long,short. This algorithm works with identity columns supported by
mysql,SQL server, DB2, Sybase database softwares. To work with this algorithm in mysql, the
EID column if employee table must be taken as identity column by applying auto increment
constraints.
Increment Identity
50
1. It is Database software independent 1. This algorithm works with those
algithm. Database sofwares which supports
identity columns.
2. Here Hibernate software directly 2. Here Hibernae software gather identity
generates identity value. value from the identity column of
Database software.
3. Does not consider deleted records while 3. Consider deleted records while
generating new identity values. generating new identity values.
4. The identity field member variable 4. The identity filed member variable
related Database table column records related table column must between
need not to have any constraints. identity column by applying auto
increment constraints.
Sequence Algorithm: This algorithm uses the sequence created/generated in DB2, Postgres,
Oracle, e.t.c., Database softwares can generate identity value of type of long, short, int. This
algorithm does not work with MySql because MySql does not support sequences if no sequence
name is specified explicitly for Hibernate software looks to use/create/Hibernate sequence
contains the logic of incrementing by 1.
Sequence created.
Employee.hbm.xml
EX: <hibernate-mapping>
<generator class="sequence">
<param name="sequence">my_seq</param>
</generator>
</id>
51
For Complete Program please refer Hibernate execution\Algorithms\sequence folder
<property name="hbm2ddl.auto">update</property>
<generator class="sequence">
<param name="sequence">my_seq</param>
</generator>
</id>
Hilo: This algorithm uses hi/lo values to generate long, short, int type identity values this
algorithm with all Database softwares. This algorithm uses helper table column values as the
source of high value similarly max-low param value while generating the identity values. The
following three are parameters of this algorithm.
Note: The helper table column value will be incremented by 1 for every identity value
generation. This algorithm uses the following formula to generate the identity value.
hi-value*(max-lo value+1)
Table created.
52
1 row created.
SQL> commit;
Commit complete.
Sequence Hilo: This algorithm also uses hi.lo algorithm to generate the identity values of type
int, long or short this uses Database sequence generated value as hi value and Max_lo param
value as lo value. The parameters are
This algorithm works with only those Database softwares which support sequences.
Sequence created.
SQL> commit;
Commit complete.
<generator class="seqhilo">
<param name="sequence">myseq1</param>
<param name="max_lo">5</param>
</generator>
</id>
53
Native Algorithm: This algorithm does not have its own behavior but dynamically fix up
identity or sequence or hilo algorithms depending upon the capabilities of underlying Database
softwares. With Oracle Native algorithm internally uses sequence algorithm (because Oralce
supports sequences) with MySql native algorithm internally uses identity. Because MySql
supports identity columns. If underlying Database software does not support both sequence,
identity algorithms then the native algorithm internally uses hilo algorithm. If underlying
Database software supports all he three algorithms then the native algorithm uses identity
algorithm internally.
Annotations: Annotations are the Java statements which can be used to perform meta data
operations and resource configurations.
1. Annotations are alternate for XML files towards performing resource configuration. Data
about data is called metadata.
2. Configuring resource in XML file and passing more details about that resource to the
underlying executing environment is called as Metadata operations or resource
configuration.
3. Configuring servlet program in web.xml file is called as resource configuration or
metadata operation. From servlet 2.5 api onwards this work can be done in .java files
using annotations.
i) Documentation annotations
ii) Programming annotations
i) Documentation annotations: These will be used in documentation comments/*…….*/.
These are available in jdk1.1 to 1.4
ii) Programming annotations: These annotations will be used for programming in Java.
These will be used as alternative for XML files for resource configuration.
These are introduced from jdk 1.5
54
Q) What is are the differences between configuring resources using XML files and using
annotations?
Servlet 2.5, 3.X, Hibernate 3.5+, 3.X, EJB 3.X, Struts 2.X e.t.c.,
i) Resource level/on the top of the class/on the top of the interface
ii) Method level on the top of the Java methods.
iii) Field level/ on the top of the Data member.
These Annotations makes resources, methods, fields to be recognized by the container or jre as
special entity.
UUID: This algorithm uses id address of current computer as base to generate identity value.
This algorithm generate identity value of type string containing decimal digits. This algorithm
will work with all Database softwares.
GUID: Uses the Database generated GUID based String as identity values. This algorithm works
only with SQL server.
Foreign: This algorithm uses id value of one Hibernate POJO class object as the id value of
another HB POJO class object. This algorithm is useful working with 1 to 1 association.
55
Hibernate software supplied some special built in tools to perform DDL operations on Database
software those are Create table, Alter table, Drop table operations.
These tools performs these activities based on the configuration in mapping files, configuration
files. To work with these tools the basic set up of Hibernate is enough.
SchemaExprot: Always create new Database table and also drops existing Database table if
necessary. To apply constraints on the table columns we can provide instructions to this tool by
using length, not null, unique and unique etc., attributes of property, id tag in mapping.
EX:
Step1: keep mapping file ready by specifying the constraints that we want to apply on Database
table.
Employeee.hbm.xml:
Step2: use SchemaExport tool from command prompt and show below.
Note: It is also not recommended to do from Command prompt. For better result use NetBeans
IDE7.1
SchemaUpdate: This tool uses the existing table if already available or modifies the existing
table if needed or creates the new Database table if table is not readily available. This tool never
drops existing table but alters the existing table if necessary.
To locate/create table:
56
To alter table:
Note: These two tools are very useful to perform DDL operations in new Database software
whose SQL queries are totally unaware to programmers. If Database software of project is
changed to postgres SQL to Oralce then programmer need not aware of the SQL queries of
Postgres SQL then he can think about using these tools to create tables in thos Postgres SQL
Database software.
Schema Validator: this tool checks whether Database table in Database software is there
according to the configurations done in Hibernate mapping file. If not there this tool will
raise the exception. This tool is not update of creating tables or dropping tables altering
tables. This tool just verifies/validates Database table according to the configurations in
mapping file.
To see these tools execution happening dynamically along with hibernate application
execution we need to work with the special property of hibernate configuration file that is
i) Create
ii) Update(popular tool)
iii) Validate
iv) Create/frop
i) Create : Internally uses SchemaExprot tool so always creates new Database table.
57
EX: <property name="hibernate.hbm2ddl.auto">update</property>
In mapping flle:
This value internally uses SchemaValidator tool and always verifies whether Database table of
Database software is there according to mapping file entries or not.
//Note: Schema Validate is not working in MyEclipse IDE. It is working with NetBeans IDE. It
is also not working in manual process also.
OUTPUT:
Hibernate: insert into SCOTT.EMPLOYEE (FNAME, LNAME, EMAIL, EID) values (?, ?, ?, ?)
Record inserted
This is note working with MyEclipse IDE, It is only working with NetBeans IDE. It is also not working
with manual process.
iv) Create/drop: This value internally uses SchemaExprot tool but creates Database table
when SessionFactory object is created and drops that Database table when
SessionFactory object is closed(Factroy.close) this value is useful to create and drop
Database tables of the project on temporary basis towards demonstrations, testing
mode of the project.
JDBC Connection pool: JDBC Connection pool is a factory that contains set of readily
available JDBC connection objects. Every Hibernate application internally contains one JDBC
connection pool represented by SessionFactory object. Our Hibernate application can work with
these types of JDBC Connection pools.
58
iii) Server managed JDBC connection pool(web server/application server)
Because of poor performance and bad features the Hibernate supplied JDBC
connection pool is not suitable for Production Environment of projects in real time
applications. But we can control this pool size property as shown below. This pool
default maximum capacity is 20.
Step3: Add Provider_class property in Hibernate Configuration file to make Hibernate Software
file to make Hibernate software working with C3P0 Connection Pool(Specify Connection
Provider class) in Hibernate.cfg.xml
//Configuration File:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">tiger</property>
<property
name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvide
r</property>
<property name="hibernate.connection.pool_size">25</property>
<property name="hibernate.c3p0.max_size">2</property>
59
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="show_sql">true</property>
<mapping resource="hibernate.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Note: If we work with NetBeans IDE we have to import C3P0 tool but in My Eclipse it is not
necessary.
Note: At the time of using C3P0 connection pooling if we violate primary key, it is not
giving any response and also the value not inserting. Even if there is no primary key the
value is not inserting.
Q) What is the JDBC Connection pool that you have used in your project Development?
C3PO, POXOL in Standalone applications, Server managed JDBC Connection pool while
working with Hibernate applications that are deployable in server.
Based on the Connection provider class that are configure in the Hibernate configuration file.
Hibernate software becomes ready to use certain JDBC connection pool while executing
applications.
To configure these Connection provider classes in Hibernate cfg file we can use
“hibernate.connection.provider_class” property.
60
iv. Develop separate file having the pool related JDBC prorperties.
Specify the above xml file name and its alias name in Hibernate configuration file.
Since proxol tool releated parameters are specified in separate XML file delete the related
properties from configuration file(driver_class, url, user name, password and etc.,)
Note: This is not executing in NetBeans IDE, It will execute in MyEclipse IDE.
At the time of using proxool connection pooling if we violate primary key, it is not giving
any response and also the value not inserting. Even if there is no primary key the value is
not inserting.
Note: The Program may run or may not run. Most of cases it is not running.So its best always go
for C3P0.
Note: It is better to go for C3P0. We have to modify one XML file no need to create another
XML so execution time will become less.
Registry Software: registry software maintains object and object references having global
visibility.
Web logic registry built- in in web logic server. Glassfish registry built-in in Glassfish server,
RMI built in jdk, COS(common object service is built in JDK, web sphere. Java applications are
use JNDI API code to talking with Registry softwares. JNDI API is built-in API of jdk
software(javax.naming and its sub packages). JDBC data source object represents JDBC
connection pool and allows to access connection objects from the Connection pool for global
visibility. This data source object will be placed in the Registry software. JDBC Data source
object means it is object of the JDBC driver supplied java class that implements
javax.sql.DataSource interface.
61
Understanding the working environment of server managed JDBC Connection Pool:
Gets JDBC
DataSource
reference from JDBC DataSource obj 7 Server Managed JDBC
Registry 5 Connection
Calls 6 2
8 Pool
getConnection
on DataSource 3
reference and (for Oracle)
gets
Connection 4
object from
JDBC
62
Connection
Pool
8
Sathya(nick name for JNDI)
DataSource
1
10
All Common objects in Connection Pool represents connectivity with same Database software.
Entire team uses single JDBC connection pool while developing the project. With respect the
diagram
1,2,3) In server type-1 or 2 or 4 driver will be utilize to interact with Database software and
create JDBC Connection pool having set of JDBC Connection objects. Objects in server JDBC
data source object will be created having representing the Connection Pool.
4) For global visibility the DataSource object reference will be placed in Registry software.
5) Client application gets DataSource object reference from Registry by using JNDI(java naming
and directory interface) code.
6,7,8) Client application calls getConenction() o DataSource object reference this call internally
uses Type-3 protocol and gets one Connection object from Connection Pool from Client
application.
63
Q) What is the JDBC driver that you have used in your project?
A) Type-3 with Type-4 while working with projects that are deployable in servers to work with
server managed JDBC Connection pool. Just Type-4 driver in standalone projects which run
outside servers.
A) Two types
EX: class.forName(“…..”)
Connection con=DriverManager.getConnection(-,-)
Download: www.commerce.bea.com
64
Jar file: weblogic.jar
The multiple projects of Company uses multiple domains of web logic installing web logic
software only once domains will be created in the software.
JDBC Driver is the bridge between Java application and Database software. Every JDBC
driver is identified which its driver class name. Naming manager is the bridge between Java
application and Registry software and every memory manager is identified with its initial context
factory class name. JDBC Connection object represents the connectivity between Java
application and Database software. To create this connection object we need JDBC properties
65
like driver class name, url, Database user name, Database password. These JDBC properties will
change based on the JDBC driver and Database software we use.
Procedure to use JDBC Connection Pool for Oracle created in Web Logic server in our
first Hibernate application:
In Hibernate.cfg.xml
<property
name="hibernate.connection.provider_class">org.hibernate.connection.DataSourceConnetionPro
vider</property>
<property name="hibernate.jndi.class">WLInitialCotextFactory</property>
<property name="hibernate.jndi.url">t3://localhost:7001</property>
<property name="hibernate.connection.datasource">sathya</property>
66
Remove driver_class, url, user name, Password properties related entries form Hibernate
Configuration file. Run the client application the above steps based application is standalone
application using the Web logic server managed Connection Pool. Which it not recommended to
do.
NetBeans IDE gives Glass Fish as built-in server we can use this Glass Fish wih or without Net
Beans IDE.
67
Using default port 3700 for IIOP.
a,C=US]
[CN=bhargav-ae185c5-instance,OU=GlassFish,O=Oracle Corporation,L=Santa
California,C=US]
Procedure to change the http port number the above domain to server:
68
<network-listener port="4848" protocol="admin-listener" transport="tcp" name="admin-
listener" thread-pool="admin-thread-pool"></network-listener>
r.log
http://localhost:4545
69
Stop the server:
70
C:\Program Files\glassfish-3.1.1\bin>asadmin stop-domain testuser
Password : adminadmin
JSP Program
AWT Frame/SWING
Applet/JApplet
Struts
JSF
Spring Application
EJB 2.X
EJB 3.X
71
When we are working with web applications by using Hibernate we have to add all jar files to lib
folder. Which is used by servlet container.
Procedure to transfer one record of Oracle Database table to MySql Database table.
One TestClient.java file, one EmpBean.java file, two mapping files( one for MySql another
for Oracle), two Configuration files.
MyCfg.ora.xml:
TestClient.java:
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
buildSessionFactory.openSession();
72
System.out.println(eb.getNo+” “+eb.getFame()+” “+eb.getLname()+” “+eb.getEmail());
Transaction tx=mysqlses.beginTransation();
Mysqlses.save(eb);
Tx.commit();
//close HB obj
Mysqlses.close();
Orases.close();
Make sure that following jar files added to the class path. Eight Hibernate regular jar files one ojdbc14.jar
one mysql-connector-3.0.8-stable.bin jar file. Compile all the .java resources and execute the TestClient
applications get(-,-), ses.load(obj, id) methods directly return the persistent state HBPOJO class object
representing the record that is selected where as ses.load(class,id) first returns proxy object and convert
that proxy object once then record is loaded into the object.
A) The object that represents temporarily presence of the real persistent state object is called
proxy object. Proxy object doesn’t represent record and does not contain data and creates new
persistent state object once record is loaded from database.
HQL:
1. HQL means Hibernate Query language. These queries are Database software independent
queries.
73
2. Hibernate software converts HQL queries into underlying Database software specific
HQL queries by using AST translator.
3. HQL Query based persistence logic is Database software independent.
4. HQL queries will be written based on HB POJO class and its member variables.
5. HQL Supports both named and positional parameters.
6. HQL supports aggregate functions, operators, conditional classes sub queries, joins and
non select operations.
7. HQL query will be represented with Query object(Object of a java class that implements
org.hibernate.QueryInterface.
8. HQL queries are not case sensitive but class names and variable names used in these
queries are case sensitive.
Limitations:
(or)
(or)
74
HQL> select eb.fname, eb.lname from EmpBean eb;
If we want to frame HQL query by specifying member variable names representing columns for
framing conditions on other operation specifying alias name for HB POJO class in the query is
mandatory. Otherwise opetional.
1. Select Queries
2. Non Select Queries (use executeUpdate() to execute these queries)
JDBC level select query execution gives JDBC ResultSet object but this ResultSet object is
not a serializable object to send over the network. So we need to write some additional logic to
move the records of ResultSet to ArrayList object and to send to the ArrayList object over the
network. HQL select query of Hibernate gives collection Framework list DataStructure so it can
be send directly over network.
Note: All the collection Framework Data structures are Serializable objects by default.
Iterator ir=q1.iterate();
While(it.hasNext())
75
{
Res.close();
Q) What is the difference between HQL and select query by using list() and iterate()?
A)
list() Iterate()
1. Select required records at a time. 1. Select required records of the table
one after another.
2. Generates single SQL select query. 2. Generates multiple SQL select
queries in these multiple queries first
select query just returns identity
values of the record and remaining
queries return the records.
3. Performs immediate initialization of 3. Performing on demand initialization
objects with selected records selected of objects with records(indicates lazy
table(indicates eagar loading) loading)
4. EX: select four records from the table 4. EX: To select four records from the
which generates single SQL select table it generates four SQL select
query. queries.
5. Gives good performance 5. Gives bad performance.
When list() is used all required records based on the given condition will be selected from the
table at once by generating single select query. When iterate() is used first generated select
query returns identity values of required records next generated select queries uses the
identity values as condition values and selects one record at a time from the table.
76
For Complete programs please refer C:\Hibernate\HQL folder
Note: HQL, EJB-QL, JPA-QL are object based query languages to develop the Database
independent queries.
i) Positional Parameters
ii) Named Parameters
int a=100;
int b=200;
q1.setInteger(0,a1);
q1.setInteger(1,b1);
for(int i=0;i<l.size();i++)
ps.Employee eb=(ps.Employee)l.get(i);
ses.close();
77
String based operation:
Query q1=ses.createQuery("select eb from Employee eb where eid>? and fname like ?");
int a=100;
String b="M%";
q1.setInteger(0,a1);
q1.setString(1,b1);
for(int i=0;i<l.size();i++)
ps.Employee eb=(ps.Employee)l.get(i);
Named Positional Parameters: When multiple parameters positional parameters are there then
there is a possibility of doing mistakes to identify the parameters through their indexes to
overcome this problem we can work with named parameters(:<name>)
int a=3;
78
String b="x%";
q1.setInteger("P1",a1);
q1.setString("P2",b1);
for(int i=0;i<l.size();i++)
ps.Employee eb=(ps.Employee)l.get(i);
Note: We can prepare HQL Query by having both positional and named parameters but we can’t
define/place positional parameter after any named parameter have been defined/placed.
int a=3;
String b="x%";
q1.setInteger(0,a1);
q1.setString("P2",b1);
79
List l=q1.list();//make Hibernate Software to execute HQL query
for(int i=0;i<l.size();i++)
ps.Employee eb=(ps.Employee)l.get(i);
Because of we shouldn’t write query like this because after named parameters we should not take
named parameters in HQL query can be representing input values and conditional values. But
these parameters can’t be taken representing HQL keywords POJO classes and POJO class
member variables.
Query q1=ses.createQuery("select eb from Employee eb where eb.eid> :P1 and eb.email like ?");
List l=q1.list();
Long l1=(Long)l.get(0);
long cnt=l1.longValue()
System.out.println("Cont of records"+cnt);
ses.close();
80
//for complete program refer page no 50and Projects folder HQLTest project open
AggregateFunction
HQL select query with multiple aggregate functions: Collection Framework data structure
allow objects as elements values arrays are objects in Java. So arrays can be placed as
element values of collection Framework data structures. The java.lang.Object class obj array
can hold any Java class object as element values and this array itselt can become element
Java.lang.Object.class.obj[]
0 1 2 3 4
values of Collection Framework data structures. If we want to class name of certain dynamic
object call getClass() on that object.
81
Executing HQL select query with multiple aggregate functions:
List l=q1.list();
Object result[]=(Object[])l.get(0);
Long res1=(Long)result[0];
long count=res1.longValue();
Long res2=(Long)result[1];
long max=res2.longValue();
Long res3=(Long)result[2];
long min=res3.longValue();
Long res4=(Long)result[3];
long sum=res4.longValue();
Double res5=(Double)result[4];
double avg=res4.doubleValue();
System.out.println("Number of records"+count);
System.out.println("Maximum of records"+max);
System.out.println("Minimum of records"+min);
System.out.println("Sum of records"+sum);
82
ses.close();
SubQuery: Query inside the query is called as sub query generally the results of sub query will
be used as the input values of outer query.
EX:
List l=q1.list();
for(int i=0;i<l.size();i++)
Employee eb=(Employee)l.get(i);
By using List
q1.setInteger(0,10);
List l=q1.list();
for(int i=0;i<l.size();i++)
Object row[]=(Object[])l.get(i);
83
//process the elements of the list
for(int k=0;k<row.length;k++)
System.out.println();
When HQL select queries are there selecting specific column values from the Database table
then the returned list data structure contains java.lang.Obejct class Object[] as element values.
By using iterate():
q1.setInteger(0,10);
Iterator itr=q1.iterate();
while(itr.hasNext())
Object row[]=(Object[])itr.next();
for(int k=0;k<row.length;k++)
84
System.out.println(row[k].toString()+" "); //prints each record
System.out.println();
When iterate() is used to execute HQL select query that select specific column values of table it
is same as List() that means on demand initialization, lazy loading multiple select SQL queries
generation will not take place in this condition.
HQL non select queries can be prepared having named, positional parameters these queries
must be executed as transactional statements from our applications.
q1.setInteger("p1",10);
Transaction tx=ses.beginTransaction();
int result=q1.executeUpdate();
tx.commit();
ses.close();
Writing HQL insert Query: HQL insert query is not given to insert the record into table with
direct values it is given to insert the record into table by selecting the record from another table.
i) HQL insert query is not given as insert into values ………….. form. It is given as select
from ….
ii) To insert single record with direct values use ses.save() or ses.persist methods.
85
Employee1 same as Employee
Create two POJO classes Employee.java, same as first Employee1.java as first application
HQL insert query is not there to insert single record with direct values it is there to insert bulk
records by gathering them from another table.
The HQL query that placed in Hibernate mapping file having logical name is called as named
HQL queries
Advantages:
1. HQL queries become globally visible queries in the multiple applications of Hibernate
environment
2. HQL queries can be used multiple session objects of Hibernate based client applications.
3. HQL queries give flexibility to programmers to modify HQL queries without disturbing
the Java source code.
Here HQL query is specific to one Hibernate Session object and it does not give global
visibility and flexibility of modification.
3. Write a logical client application to get access to named HQL query and to execute that
query by using multiple Session objects
86
<: and >: and etc., are called entities of XML these are given to generate special symbols.
Note: Be careful while typing Named queries in Hibernate mapping file having the utilization of
less that symbol. Because this less than symbol takes XML meaning (as beginner of sub tag) to
suppress this meaning and to treat it as a conditional operator we can use either entity <: or
Pagination : The multiple Database records of table in mapping pages by page format is called
Pagination. HQL queries support pagination for that we need to use setFirstResults(-),
setMaxResults methods of org.hibernate.Query interface.
FF001
FF002
FF003
87
Public searializable generate(SessionImplementation session, Object obj)
return generateFolder(Session);
9) Develop and execute the client application having the logic to insert the record.
Native SQL: IF certain persistence operations are not possible with HQL queries, HQL queries
are complex to write then the Database software development Native SQL queries to develop
Hibernate persistence logic.
Note: SQL query object means it is the object of a Java class org.hibernate.SQLQuery interface
and this interface is the sub interface of Query interface.
1. Native SQL results must be mapped with Hibernate Datatypes or HBPOJO classes
receives the results through objects.
2. Hibernate Data types are the bridge data types between Java datatypes and JDBC data
types.
88
3. HQL queries written based on the POJO classes and its member variables. Native SQL
queries will be written based on Database table and Database table columns.
4. There are two types of Native SQL Select queries.
i) Entity Queries(selects all the column values of Database table)(Results must be mapped
with HB POJO class)
ii) Scalar queries (Selects specific column values of Database tables) results must be
mapped with Hibernate Data types.
q1.addEntity(Employee.class);
List l=q1.list();
for(int i=0;i<l.size();i++)
Employee eb=(Employee)l.get(i);
89
Note: We can’t iterate() to execute native SQL select queries when used
java.lang,UnSupportedException will be raised.
In Employee.hbm.xml
<sql-query name="test1">
</sql-query>
In TestClient.java
q1.addScalar("fname", Hibernate.STRING);
q1.addScalar("email",Hibernate.STRING);
List l=q1.list();
for(int i=0;i<l.size();i++)
Object row[]=(Object[])l.get(i);
for(int k=0;k<row.length;k++)
90
System.out.println();
StandardBasicMappingTypeSTRING:
Note: Mapping scalar query results with Hibernate data types is opetional. Executing Native
SQL scalar query having aggregate functions.
Q) Why iterate(-) is not applicable on native SQL queries and why it is applicable on HQL
queries?
A) when iterate(-) is used on HQL query the Hibernate software generates multiple select
queries based on Single HQL query but this kind of multiple queries generation is not
possible while working with native SQL query because of this Hibernate software sends and
execute native SQL query in its database software without any modifications and
conversions. Due to these reasons iterate(-) is not applicable on native SQL queries.
<sql-query name="test1">
</sql-query>
2. Access the query in the client applications and execute the query
Query q1=ses.getNamedQuery("test1");
q1.setInteger(0,32);
q1.setString(1,"Tamanna");
q1.setString(2,"Bhatia");
q1.setString(3,"[email protected]");
Transaction tx=ses.beginTransaction();
int result=q1.executeUpdate();
91
System.out.println("number of records affected"+result);
We can perform DDL operations on Database using Native SQL queries but we can’t pass the
input table names and column names as parameter values that means they must be hard coded
directly in the query.
We can perform even pagination on the results given by native SQL queries.
Calling values from PL/SQL stored procedures and functions: Persistence logics are
centralized, reusable or globally accessible logics for multiple applications of module or for
multiple modules for a project then it is recommended to develop these persistence logics in
Database software as PL/SQL procedures and functions.
To call procedure:
{call <procedure-name>(?,?,?-----)}
92
To call function:
{?=call<(function-name(?,?,?---)}
PL/SQL procedure must have first parameter as OUT parameter having type (sys-ref cursor)
(or)
JVM
Application LocalClient
Machine2
JVM
Remote Client
JVM2
Remote Client
A) If an application and its client reside in same JVM then that client is called as local Client to
Client application. If application and its Client resides in two different JVMs of same or two
different JVMs of same or two different computers then the client is called as Remote Client.
1. Hibernate is not distributed technology. So its persistence logic can’t be accessed from
remote Client(that means allow only local clients)
2. Hibernate internally generates JDBC code. This process degrades the performance.
3. Calling PL/SQL procedures and functions is very complex in Hibernate (Procedures and
functions can’t be developed freely)
4. Pagination is not possible on the results generated by PL/SQL procedures and functions.
5. Hibernate does not support nested, distributed transactions.
6. Hibernate criteria API does not support non select transactions.
7. Lazy loading or on demand initialization is not possible with native SQL queries and etc.,
EJB, Spring JEE module technologies are distributed technologies. So those applications
allows both remote and local clients.
93
Criteria API (working with org.hiebrnate.criterian): Criteria means condition. Which
allows to develop the entire persistence logic by using Java statements(no queries) using
classes and methods.
Limitations:
Note: Criteria API with Conditions are not working with hibernate 3.6.5. But these are
working with hibernate 3.2.5 in Net Beans, My Eclipse IDEs.
A) Criteria object represents the whole hibernate criteria API based persistence logic . In that
Criterian object represent one condition. Criteria Object means it is the object of a class that
implements org.hibernate.Criteria interface. To create this object we use
Session.createCrieteria(-). Criteria object means it is the object of a class that implements
94
org.hibernate.crieteria.Criterian interface. To create this object we use methods of Restriction
class.
When multiple conditions are added Criterian API by default they will be execute with
And class.
If we feel framing conditions through Java methods is very complex then we can use expression
to frame those conditions as SQL statements.
Criteria ct=ses.createCriteria(EmpBean.class);
ct.add(cond);
List l=st.list();
for(-)
----
Note: The versioning feature of Hibernate does not keep track of modifications if records are
modified directly without selecting them into application.
Note: If modifications will happen in Database side without using hibernate those modifications
never reflet.
Working with Files (Large Objects): Working with File is nothing but working with large
objects there are two types of large objects.
95
Large Objects
BLOB CLOB
All major Database softwares giving support for BLOB, CLOB data types.
Hibernate supports BLOB and CLOB objects based programming. While developing
matrimony, JOB potal, Pay roll and etc., applications we need to insert and retrieve document,
image files by taking the support of BLOB, CLOB data types.
Tip: Keep LargeObjects.java file in a package. We can retrieve any where whether we would
like to use it.
Hibernate Filters: Hibernate Filters allows us to place conditions in mapping file having global
visibility. Hibernate Filter global, named, parameterized filter that can be enabled or disabled
for a particular Hibernate session. The condition of Hibernate Filter can be used on multiple
Hibernate Session objects having abilility to enable or disable filter
In Mapping File:
96