You are on page 1of 94

B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.

com Nataraj Sir 11:00 am Batch



1

Persistency: The place where data can be saved permanently is called persistent store.
EX: Files, Database software
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)
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

2

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
avg=tot/3 business logic
Generate rank for the student based his marks avg*(business logic)
Display student details
including tot, avg rank for end user(Presentation logic).
End user: The operator of application is end user.
Note: If there is no separate business logic then persistent logic itself acts business logic of
application.
Java app----I/O Streams---------------------- Files
Java App-------JBDC, o-r mapping----------- Database Software.
Java App--------JDBC+OQL+ORDBMS-----ODB Software (Versant, Poet)
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.
To overcome this problem we use Database software as persistent stores.
Object Database Software: The Database software which can store software object as Database
table column value is called Object Database Software.
public class marks
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

3

{
-------------
---------------
}
marks mk=new marks();
mk(marks class obj)





Object Database Software









Object Database softwares failed in the industry because of following reasons.
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.
m1=30
m2=50
m3=70

Student Tab(Database Tabel)
Sno sname marks
10 Siva m1=30, m2=50, m3=70
11 Bhargav
12 Reddy
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

4

ii. Generating reports from the Database table of Object Database softwares is complex
process.
Note: SQL Queries are Database dependent queries.
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.
EX: Desktop games and mobile games.
In medium scale organizations Database software is used as persistence store ad JDBC to
develop the persistence logic.
EX: Office automation application.
Payroll applications
Library management application and e.t.c.,
In Large scale organizations Database software used as persistent store and use or mapping
style persistent logic.
EX: Banking applications/credit card applications and e.t.c.,
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
cant be sent over the network because it is not serializable object.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

5

8. In JDBC programmer have to Write more common logics along with application
specific logics in every JDBC application (Scratch level coding is required).
Q) What is o-r mapping?
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.
ORM Softwares Vendors priority
EJB entity bean components SUN Microsystems (Oracle) least
Hibernate SoftTree (Red Hat) 1 (90% using)
Ibatis Apache 4
JDO (Java Data Objects) Adobe least
Top Link Oracle least
OJB (Object java Bean) Apache 3
JPA SUN Microsystem (Oracle) 2

Class student o-r mapping(XML File)
{ Student (Java class) Student_Tab(Database Table) Database
int sno; java classes sno sno table
String sname; member variables Sname Sname columns
float avg; avg avg
------------
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

6

------------ Methods
---------------
}

Java applications o-r mapping persistence logic
St1(Student class object)


Synchronization







Synchronization







Stno : 101
Sname: Janu Sonu
avg: 78.67
Stno : 102
Sname: Vijay
avg: 79.99



Sno Sname avg
101 Jani Janu 78.67
102 Vijay 79.79
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

7

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.
EX: Hibernate, Struts, Spring.
Understanding Hibernate abstraction layer on JDBC program:
1. Register JDBC driver with DriverManager service.
2. Establish connection with Database software.
3. Create JDBC statement object.
4. Send and execute query in Database software.
5. Gather results and process the results.
6. Close JBDC objects.
7. Take care of Exception handling.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

8

8. Perform Transaction management (if necessary).

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.
Hibernate based Java application:
1. Create a Session factory, session objects.
2. Perform persistence operations on Database table using objects.
3. Gather and process the results.
4. Close session factory, session objects.
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
1. Web Framework softwares
2. ORM Framework Softwares
3. Java-jee Framework softwares

1. Web Framework softwares: Web Framework softwares provides abstraction layer on
Servlets, JSP, Core technologies and simplifies developing of web applications.
EX: Struts, JSF, Web services, Tapstrey, Spring web MVC.
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.
EX: Hibernate, OJB, Ibatis, Toplink e.t.c.,
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:
1. Light weight ORM Framework Software.
2. Allows us to Database software independent persistence(o-r mapping persistence logic)
3. Supports POJO and POJI model programming.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

9

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.
EX: Transaction Management, Security, JDBC Connection Pooling and e.t.c.,
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.
public void bml()
try
{
------------- source code which may checked exception
-------------
}
Catch(SQLException se)
{
Throw new arithmetic exception();// Exception Rethrowing
}
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

10

}
11. Allows us to develop PL/SQL procedures/ functions of Database software.
12. Allows to build object based relationship one to one, one to many and e.t.c.,
13. Gives annotations support in programming as alternate to XML files.
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.
15. Easy to communicate and apply.
16. Supports two levels catching and buffering.
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
{
---------
----------
}
Test is POJO class
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

11

EX2:
class Test implements XYX
{
-----------
------------
--------
}
XYZ is user defined interface not extending from other interfaces.
EX3:
Class Test extends ABC
{
--------------
--------------
}
ABC is user defined class and not extending from other class.
EX4:
Class Test implements java.rmi.Remote
{
---------------
---------------
}
Test is POJO it is RMI API independent.
EX5:
Class Test extends HTTPServlet
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

12

{
------------
-------------
}
Test is not POJO class it is servet API dependent.
EX6:
Class Test implements java.io.Serializable
{
-----------------
--------------------
}
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:
Class Test extends Thread
{
--------------
-------------
}
Text is POJO.
EX:
Class Test extends ABC
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

13

{
-------------
-------------
}
ABC is not a POJO
EX:
Class Test
{
Public void main()
{
--------------- // Hibrenate API used here
--------------
}
Test is POJO because Hibernate API inside the method.
EX:
Public class Test implements XYZ
{
--------------
-------------
}
Text is not POJO
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.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

14

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.
Some example POJIs:
Interface Demo
{
-----------------
------------------
}
Demo is POJI .
Interface Demo extends java.rmi.Remote
{
---------------
---------------
}
Demo is not POJI. Demo is RMI API dependent.
Interface Demo extends java.lang.Clonable
{
-----------------
-----------------
}
Interface Demo extends Demo1
{
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

15

--------------------
---------------------
}
Demo1 is user defined interface not extending form other interfaces. So Demo is POJI.
Interface Demo extends XYZ
{
------------------
---------------------
}
Interface XYZ extends javax.servlet.Servlet
{
--------------
---------------
}
XYZ is not 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
extract zip file and keep it in C drive.
When we place Hibernate persistence logic in our applications then our applications
become client to Database software but not Client to Hibernate Software.

B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

16






Java application(Clint to Database)















Hibrnate Code
Persistence
Loic

B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

17

To develop Hibernate persistence logics we need to following main resources.
Hibernate cfg file(XML file)(HB file)
Hibernate mapping file(XML File) (HB file)
Hibernate persistence class(Java bean class, JDBC driver e.t.c.,-----)
Understanding Hibernate architecture:
Using Hibernate we just develop persistence logic and it cant 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.

3
Client App/Component Database Hibernate Resource Server Software
1







5



Database Software
Java appl/AWT Swing App
Servlet App(jsp comp/prg)
Struts APP/JSF
EJB Comp/ Swing Comp

---------------------------------------
Hibernate
Persistence
class(Java Bean)
Hibrnate cfg
file
Hibernate
Mapping
File(XML)

4
Object based o-r
mapping
persistence
logic 2

N
E
T
W
O
K
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

18

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.
Hibernate Configuration File:
<any filename>.XML can be taken as Hibernate configuration file. If no file name is
specified explicitly the Hibernate software is activated in the Client application generally
looks like hibernatecfg.xml as default configuration file.
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.connection.driver_class (for JDBC driver class)
hibernate.connection.url (For url)
hibernate.connection.username (For user name)
hibernate.connection.password (For password)
hibernate.dialet

mapping file name
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)

Q) What is use of Hibernate dialect property of hibernate configuration file.
A) The values specified in this property guides hibernate software in the following ways.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

19

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.
EX: Oracle 9i org.hibernate.dialect.Oracle9i dialect.
Oracle 10g Oracle10g dialect
Oracle 11g Oracle any version hibernate.dialect.Oracledialect
MySQL Hibernate.dialect.MySQL 5 dialect and e.t.c.,
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.
Hibernate Mapping file:
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.,
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

20

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.
Most of the Web projects will be developed based on MVC2 architecture.
M Model Layer Business logic Persistence logic.
V View Layer Presentation Logic
C Controller Layer Integration logic------/ connectivity
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
Conclusion: Always use model layer for persistence logic.
Various possible technologies in View Layer:
HTML, XHTML, JSP, Velocity, Free Marker.
Various possible technologies in Controller Layer:
1. Servlet
2. Servlet Fileter
Various web Framework softwares to develop View, Controller logics:
Struts, JDF, Web Framework, Spring MVC, Tapstrey, Cocoon, OAF(Oracle activation
Framework) and e.t.c.,
Various possible technologies to develop business logic in Model Layer:
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

21

EJB, RMI, Webservices, Java bean/class HTTP involker Hessian and Barlup, CORBA(
Common Object request Broker Architecture), Spring
Various possible technologies for developing persistence Model Layer:
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
Spring JEE Application

Persistence Layer
Spring ORM Module Hibernate

Data Layer
Database Software(Oracle)

Client applications of Hibernate maintain HB POJO calss object(Hibernate persistence class
object) in there 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.

B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

22

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.












B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

23

Understanding SessionFactory and Sessionstate object:














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.
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

creates




creates


Persistence
context
rep

Ssyn

Hibernate
SessionFactory
object

Configuration class
Object
Hibernate Session object
No:101
Name:Siva
Avg:90

Stu.db
sno sname avg
10 raj 70
con
con

con
con

B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

24

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.
Hibernate Session Object: It means it is object of Java class that implements
org.hibernate.Session(I).
Immutable: Immutable object mans modification done in the data of the objects wont 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)





String buffer sb=new StringBuffer(hello);


S
hello
String class
obj
Hello how
String class
obj
Hello how

hb
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

25


Sb=sb.concat(how);
Hibrenate SessionFactory objects are immutable, Hiberate Session objects are immutable,
Session objects are mutable.
Code in Client application to create Hibernate SessionFactory, Session object by activating
Hibernate Software:
//Activating Hibernate Software
Configuration cfg=new Configuration() //instance factory
//locate and read method of Hibernate cfg file.
Hibernate config file.cfg=cfg.configure(\hibernate.cfg.xml);
cfg contains the entries placed hibernate configuration file.
//create hibernate SessionFactory object.
SessionFactory factory = cfg.buildSessionFactory
//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.
//create hibernate Session obj
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.


Persistence operations in Hibernate


B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

26


Single Row operations Bulk Operations

Call various methods
On Hibernate Session obj HQL
save(-) Native SQL
persistence(-) Criteria API(OBC)
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.
Configuration File:It is available in C:\hibernate-distribution-3.6.5.Final\project\etc location.
We have to make some modifications to this file.
//hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

27

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

<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"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

28

<id name="Eid" column="EID"></id>
<property name="Fname" column="FNAME" />
<property name="Lname" column="LNAME"/>
<property name="Email" column="EMAIL"/>
</class>
</hibernate-mapping>
//Employee.java
public class Employee
{
//declare Bean Properties
//Declare member variables
private int eid;
private String fname,lname,email;
//write setXxx(-) and getXxx()
public void setEid(int eid)
{
this.eid=eid;
}
public int getEid()
{
return eid;
}
public void setFname(String fname)
{
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

29

this.fname=fname;
}
public String getFname()
{
return fname;
}
public void setLname(String lname)
{
this.lname=lname;
}
public String getLname()
{
return lname;
}
public void setEmail(String email)
{
this.email=email;
}
public String getEmail()
{
return email;
}
}

B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

30

//TestClient.java
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class TestClient
{
public static void main(String args[])
{
//Activate Hibernate Software
Configuration cfg=new Configuration();
//make hibernate software locating and reading cfg file
cfg=cfg.configure("/hibernate.cfg.xml");
//create SessionFactory obj
SessionFactory factory=cfg.buildSessionFactory();
//create HB session obj
Session ses=factory.openSession();
//write o-r mapping persistence logic
//create object for HB POJO class with data
Employee eb=new Employee();
eb.setEid(101);
eb.setFname("rakesh");
eb.setLname("rao");
eb.setEmail("123422");
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

31


//make HB software insert record
Transaction tx=ses.beginTransaction();
ses.save(eb);
tx.commit();
//close Stream objects
ses.close();
factory.close();
}
}
//OUTPUT:
C:\hbprograms\Demo1>javac *.java

C:\hbprograms\Demo1>java TestClient
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further detail
s.

SQL> select * from employee;

EID FNAME LNAME EMAIL
---------- -------------------- -------------------- --------------------
101 rakesh rao 123422
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

32


For Complete Program Please refer Hibernate execution \CURD\save(-) folder
List of jar files:
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

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
2-7)Dependent jar files to hibernate3.jar(Available in hibernate3.6-home\lib\required foleder)
8)Dependent jar file to hibernate3.jar(available in<hibernate3.6>home\lib\jpa folder.
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
driver class name: oracle.jdbc.driver.OralceDriver
jdbc url : jdbc:url:jdbc:oracle:thin:@<host name>:<port number>:<service id>
jar file: ojdbc14 jar(jdbc 3 spe and jdk 1.5/1.6)
ojdbc6.jar (jdbc4 and jdk1.6)(oracle 11g)
iii)Develop and save following resource.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

33

While developing first application of Hibrnate we can use one of the following four ways to
make java tools recognizing hibernate API.
i) Copy 8+1 jar files of hibernate to java.home\jre\lib\ext folder(permanent)
ii) Add the address locations of 8+1jar files of Hibernate to MyComputer environment
variables class path.
iii) Perpare batch file to class path as shown below and run that batch file on every
command prompt window.
iv) Add the address locations of 8+1 jar files of Hibernate in Command prompt each and
every time.
Q) What is the difference between working with class path and working with ext folder?
Class path Path
1. Allows both jar files and directories
2. Gives global visibility entries(visible to
multiple jdks)
3. New command prompt should be open
to recognize added values.
4. Points to original location of jar,
directories and uses them directly
1. Allows only jar files.
2. Visible to specific jdk.

3. Not required.

4. Needs another copy of jar files.

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
||
||
<Property name=show_sql>true</property>
<mapping resource=employee.hbm.xml/>
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

34

</session-factory>
</hibernate-configuration>
The word hibernate is optional in Hibernate Configuration file peroperties.
TestClient.java:
Configuration cfg=new Configuration();
Cfg=cfg.configure();
Makes the activated hibernate software taking hibernate.cfg.xml file of current directories as
default hibernate configuration file.
Configuration cfg=new Configuration;
Cfg=cfg.configure(/mycfg.xml);
The activated software using mycfg.xml file of current directory as hibernate configuration file.
Configurattion cfg=new Configuration();
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)
EX: SAX parser. Simple API for processing.
DOM Parser: Document object model.
DOM4J: Document object model for java
JDOM: Java document object model.
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()
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

35

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.
Ses.close(): This method performs
a) Close the connection between Java application and Database software.
b) Close the persistence context and makes all persistent state objects as the detached state
objects.
factory.close():
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()
What happens when ses.save(eb) is called:
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.
Inserting a record by persistent():
Transaction tx=ses.beginTransaction();
Ses.persistent(eb);
Tx.commit();
For Complete Program Please refer Hibernate execution \CURD\persist(-) folder.
Q) What is the difference between save(-) and persit(-)?
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

36

Save() Persist()
1. Session.save() first generates the
identity value then inserts the record
and also returns the generated identity
value.
2. Prototype of Session.save(-) is public
serializable(object obj) throws
HibernateException.
1. Session.persist(-) also insert the record
by generating identity value.


2. Prototype is public void persist(object
obj) throws 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.
public serializable save(object obj) throws HibernateException
{
---------------
----------------
//some JDBC code
}
Catch(SQLException se)
{
throw new HibernateException();
}
return idvalue;
}
Catching identity value when save(-) is called:
Transaction tx=ses.beginTransaction();
Integer idval=(Integer) ses.save(obj);
System.out.println(identity value=+idval);
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

37

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.
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.

Updating record with merge days:
Transaction tx=ses,beginTransaction();
Ses.merge(eb);
tx.commit();
For Complete Program Please refer Hibernate execution \CURD\ merge(-) folder.
Q) what is the difference between session.merge(-) and session.update(-)?
Session.update(-) just looks to update an existing record where as session.merge(-) updates an
existing record if record is available. Ohterwise inserts new record in the Database table utilizing
the data of given object.
Prototypes:
1. Public void update(Object object) throws HibernateException
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

38

2. Public object merge(Object object) throws HibernateException
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);
1. eb is Transient state object.
2. Persistent state object representing newly inserted/updated record.
Inserting/Updating record by using session.save() or session.update(-):
Transaction tx=ses.beginTransaction();
ses.saveOrUpdate(eb);
tx.commit();
-----------------
void saveOrUpdate(Object object) throws HibernateException
Q) what is the difference between session.merge(-), session.saveOrUpdate(-)?
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);
For complete program please refer Hibernate execution \CURD\saveOrUpdate(-) folder

To delete the record:
EmpBean eb=new EmpBean();
eb.setEid(102);
Transaction tx=ses.beginTransaction();
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

39

ses.delete(eb);
tx.commit();
For Complete Program Please refer Hibernate execution \CURD\delete(-) folder.
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.
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.
EmpBean eb=new EmpBean();
eb.setNo(101);
eb.setName(Siva);
eb.setLname(reddy);
eb.setMail(x@y.com);
JDBC Hibernate
1. Core technology for developing
persistence logic.
2. Develops SQL queries based
persistence logic.
3. Persistence logic is Database software
dependent.
4. Given by SUN Microsystem.
5. Internally uses streams.
6. Talk with Database software directly.
7. Suitable for medium scale applications.
8. Lazy loading not possible when we call
session.
1. Framework to develop persistence logic
2. Develops object based persistence
logic(or mapping).
3. Persistence logic is Database software
independent.
4. Given by SoftTree (Red Hat)
5. Internally use JDBC.
6. Talks with Database software by
generating JDBC code.
7. Suitable for large scale applications.
8. Does not support lazy loading.

B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

40

When we call session.save(-), session.persist(-) with transient state HB POJO class
object then they insert hibernate software to insert the record when these methods are called
having modified persistence state object then perform update operation on the record.
The overloaded form of session.load(-,-):
i. Public object load(class HBPOJO class, serializable id)
ii. Public void load(Object HBPOJOobj, serializable id)
Example to select the record by using session.load(obj, id):
EmpBean eb=new EmpBean();
ses.load(eb,103);
System.out.println(eb.getEid());
For Complete Program Please refer Hibernate execution \CURD\load(obj,id) folder
***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);
System.out.println(eb.getEid()+" "+eb.getFname()+" "+eb.getLname()+" "+eb.getEmail());
For Complete Program Please refer Hibernate execution \CURD\load(class,id) folder
***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.
So we can be written like this.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

41

Q) what is difference between session.load(obj,id) and session.load(class, id)
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
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)
selecting record by using session.get(class,id)
EX: EmpBean eb=(EmpBean)ses.get(EmpBean.class,109);
System.out.println(eb.getEid()+" "+eb.getFname()+" "+eb.getLname()+" "+eb.getEmail());
Note: There is no session.get(obj,id).
Q) what is the difference between session.load(obj,id) session.get(obj,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.


Q) what is difference between session.load(class, id) session.get(class,id)?
Session.load(class ,id) Session.get(class,id)
1. Performs lazy loading of record from
Database table.
2. Throws
Exception(ObjectNotFoundExceptipn)
when record is not found to select.
1. Performs eagar loading of record form
Database table.
2. Does not throw any Exception.


B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

42

3. Suitable large scale applications. 3. Suitable in small scale applications.

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.
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
109 sivsh rao kir
103 sivsh rao kir2
Here kir,kir2 are two mail ids. So we have to change these things so we use flush(-) at the ending
of ses.close().
So now output in Oracle software is
109 sivsh rao gir
103 sivsh rao gir2
Without using flush(-) we cant do these things.

EX: EmpBean eb=(EmpBean)ses.get(EmpBean.class,109);
System.out.println(eb.getEid()+" "+eb.getFname()+" "+eb.getLname()+"
"+eb.getEmail());

EmpBean eb1=(EmpBean)ses.get(EmpBean.class,103);
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

43

System.out.println(eb1.getEid()+" "+eb1.getFname()+" "+eb1.getLname()+"
"+eb1.getEmail());

eb.setEmail("gir");
eb1.setEmail("gir2");
ses.flush();
ses.close();
factory.close();
For Complete Program Please refer Hibernate execution \CURD\flush(-) folder
Performs synchronization persistent state objects to table rows.
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.
Example code in TestClient.java:
EmpBean eb=(EmpBean)ses.get(EmpBean.class,109);
System.out.println(eb.getEid()+" "+eb.getFname()+" "+eb.getLname()+"
"+eb.getEmail());
try
{
Thread.sleep(2000);
}
catch(InterruptedException ie)
{
System.err.println("hello");
}
ses.refresh(eb);
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

44

System.out.println(eb.getEid()+" "+eb.getFname()+" "+eb.getLname()+"
"+eb.getEmail());

ses.close();
factory.close();
For Complete Program Please refer Hibernate execution\CURD\ refresh(-)folder
Mysql: Type: multiuser Database software
Version: SUN Microsyste(Oracle)
Default: 3306
To download software: www.mysql.com
www.dev.mysql.com open source Database software.
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 Database 1 Logical Database2



Logical Database3
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

45

(Physical Software like Oracle software , mysql softaware)
In Oralce logical Database name is nothing sid(like orcl)
Orcl Database software installation gives one default logical Database(orcl)
Mysql Database installation gives one logical Database(sid)


C;\mysql\bin\bin\mysql\bin
After installing mysql 4.x software we need to activate that software by using
<Mysql_home>\winmysql
Procedure to know existing username password and modify in mysql 4.x:
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.
Procedure to create logical Database and Database table in mysql 4.x:
1. Activate mysql 4.x software
2. Launch sql prompt of mysql software.
<mysql_home>\bin\mysql tool
3. Create logical Database <mysql> create Database mydb;
4. Create employee table having records in the logical Database mydb1.conn mydb1.
5. <mysql> create table employee(eid int(5), fname vatchar(10), lname varchar(10));
Inserting values:
Insert into employee values(1010,rajesh,rao,x@y.com);
Note: Database name is orcl or test, Database software name is Mysql, Oralce.
Procedure to know existing username password and modify in mysql:
Right click on traffic signal(System tray area)
Show me my.Inf setup
Tab view and modify user, password values save modification yes right click activate
mysql software by using above password.
4.x setup
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

46

Procedure to create logical Database and Database table in mysql 4.x:
Step-1:
1. Activate mysql 4.x software
2. Launch sql prompt of mysql software
<mysq1_home> \bin\mysqltool
3. Create logical Database mysql> create database mydbl;
4. Create employee table having records in the Database mydb1 conn db1;
<mysql_home>create table employee(eid int(5),fname varchar(10),lname varchar(10));
Insert into employee values:
Insert into employee values(1010,rajesh,rao,x@y.com);
Select * from employee
In the above environment our Database software is mysql4.x our logical Database is myDb1.
Our database name is mydb1
The Devex company supplied Type-4 driver.
Type-4 mechanism based driver for mysql is called as Connector/JDBC driver.
Mechanism:Type-4
Target Database software : mysql
Jdbc driver class: org.git.mm.mysql.Drivercom.mysql.jdbc.Driver
url: jdbc:mysql:///<logical DB> (or) jdbc:mysql:/hostname:<portnumber>/<logical DB>
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
Jar file that represents this JDBC driver.
Mysql-connector-java-3.0
This jar file available in dewx.com or www.dewsql.com
Procedure to make first Hibernate application interacting with mysql software:
1. Keep first application ready to use.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

47

2. Keep following entries in the Hibernate configuration file.
Org.git.mm.mysql.mysqlDriver
3. Compile and execute client application.
Note: in XML files Hibernate programming <!DOCTYPE> statement is mandatory
NOTE: SQL yog is suitable for developing mysql without mysql knowledge.
Q) Can we develop Hibernate application without configuration file?
A) Yes, possible but not recommended to develop.
Configuration cfg=new Configuration();
Cfg.setProperty(Connection.driver_class,oracle.jdbc.driver.OracleDriver);
Cfg.setProperty(hibernate.connection.url,jdbc:oracle:thin:@localhost:1521:orcl)
-----------
--------
//specify the mapping file
Cfg.addFile(employee.hbm.xml);
//create HB SessionFactory object
SessionFactory factory =cfg.buildSessionFactory();
//create HB session obj
Session ses=factory.openSession();
Limitations with above code:
i. There is no possibility to modify configure hibernate configuration values without
recompiling source code.
ii. For certain properties we cant take hibernate word in property name as optional. Some
miscellaneous properties like show_sql will not work even through they are
configured.
Note: It is always recommended to use Hibernate Configuration file.
For Complete Program please Hibernate execution\HibernateNotConfFile folder
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

48

Q) Can we develop Hibernate application without mapping file?
A) Yes, By using Hibernate annotations in the Hibernate persistence class.
Chaining:
Calling one method on the results of the another method in a class is called chaining.
EX: int len=new String(hello how are you).substring(2,7).concat(123).length();//
Output is 9.
EX2: Session ses=new
configuration().configure(/mycfg.xml).buildSessionFactory().openSession();
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.
MyEclipse: MyEclipse=EclipseIDE+built in plugin
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
2. Does not provide builtin plugins to
work with advanced technologies but
allows to add plugins.
3. Suitable for small scale projects.

1. Commercial
2. Provide built in plugins and allows to
add plugins externally.

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:
Type: IDE software fo Java Environment.
Vendor: Eclipse org
Version: 8.x(compatable with jdk 1.5,1.6)
Commercial IDE.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

49

For help details: www.myeclipseide.com
Gives Tomcat as default server and allows configuring other servers.
Reverse Engineering: To Generating POJO class mapping file based on Database table.
Procedure to develop first application by using MyEclipse8.X IDE:
Refer Working with MyEclipse MSWord document.
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
identity values dynamically. Every algorithm is having one nick name and class name if no
algorithm is configured the default algorithm is Assigned
Nick name Algorithm class name
1. Assigned
2. Increment
3. Identity
4. Sequence
5. Helio
6. UUID
7. GUID
8. Native
9. Select
10. Foreign
org.hibernate.id.AssignedGenerator
org.hibernate.id.IncrementGenerator
org.hibernate.id.IdentityGenerator
org.hibernate.id.SequenceGenerator
org.hibernate.id.TableHelioGenerator
org.hibernate.id.UUIDGenerator
org.hibernate.id.GUIDGenerator
no class
org.hibernate.id.SelectGenerator
org.hibernate.id.ForeignGenerator

i) Make sure that algorithm is compatible with underlying Database software.
ii) Make sure that algorithm generated value type is compatible to store in the identity field
member variable.
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.
For Complete program please refer Hibernate execution\Algorithms\Increment folder
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

50

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.
Q) Difference between Increment and Decrement algorithms?
Increment Identity
1. It is Database software independent
algithm.

2. Here Hibernate software directly
generates identity value.

3. Does not consider deleted records while
generating new identity values.
4. The identity field member variable
related Database table column records
need not to have any constraints.

1. This algorithm works with those
Database sofwares which supports
identity columns.
2. Here Hibernae software gather identity
value from the identity column of
Database software.
3. Consider deleted records while
generating new identity values.
4. The identity filed member variable
related table column must between
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.
EX1: With user defined sequence creation
Step1: Create sequence in Oracle Database software.
SQL> create sequence seq1 start with 20 increment by 5;
Sequence created.
Step2: Configure sequence algorithm by specifying the above sequence name in
Employee.hbm.xml
EX: <hibernate-mapping>
<class name="EmpBean" table="EMPLOYEE">
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

51

<id name="Eid" column="EID">
<generator class="sequence">
<param name="sequence">my_seq</param>
</generator>
</id>
For Complete Program please refer Hibernate execution\Algorithms\sequence folder
EX2: Utilizing the default Hibernate sequence
Step1: Add the following property in the configuration file.
<property name="hbm2ddl.auto">update</property>
Step2: Configure sequence algorithm in mapping file.
<id name="Eid" column="EID">
<generator class="sequence">
<param name="sequence">my_seq</param>
</generator>
</id>
For Complete Program please refer Hibernate execution\Algorithms\UserSequence folder
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.
i) Table To specify helper table name
ii) Column To specify helper table column name(this value becomes the source of hi
value)
iii) Max_lo To specify lo value.
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)
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

52

The column value in helper class table.
EX: Create helper table having column with value.
SQL> create table mytab(mycol number(4));
Table created.
SQL> insert into mytab values(10);
1 row created.
SQL> commit;
Commit complete.
For Complete Program please refer Hibernate execution\Algorithms\Hilo folder
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
sequence The Database sequence name as the source of hi value.
Max_lo use the value as the source of low value.
This algorithm works with only those Database softwares which support sequences.
Step1: Create sequence in Database software

SQL> create sequence myseq1 start with 10 increment by 2;
Sequence created.
SQL> commit;
Commit complete.
Step2: Configure sequence seqhilo algorithm in mapping file.
<id name="Eid" column="EID">
<generator class="seqhilo">
<param name="sequence">myseq1</param>
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

53

<param name="max_lo">5</param>
</generator>
</id>
For Complete Program Please refer D:\Frameworks\Hibernate
execution\Algorithms\SequenceHilo folder
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.
Syn:@ <connection_name>(param 1=val1, param2=val2.)
There are two types of annotations in Java
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
Examples for documentation annotations:
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

54

@author, @since, @param, @throws and e.t.c.,-----------
(refer .java files of <java_home\src.zip file)
Examples of Programming annotations:
@Override, @FailSafe and e.t.c.,
Q) What is are the differences between configuring resources using XML files and using
annotations?
XML Files Annotations
1. XML parsers read data from xml files.

2. XML parser is heavy weight software
application so working with XML files
for resources configuration
3. Gives bad performance but gives good
flexibility of modification with out
modifying the source code
1. Annotations are placed in .java files
directly
2. Annotations are underlying runtime
environment or container. So these are
recognized directly by JVM.
3. Gives good performance, flexibility is
not there because each and every time
we have to compile .java file.

The technologies which are giving support to annotations:
Servlet 2.5, 3.X, Hibernate 3.5+, 3.X, EJB 3.X, Struts 2.X e.t.c.,
Every annotation is special @interface containing methods representing annotation parameters.
Annotations of Standalone applications will be recognized and processed by jre/JVM ,
Servlet alllication will be recognize by servlet container(Catalina), For EJB EJB container, For
Hibernate applications Hibernate software.
We can apply annotations at three levels of Java source code.
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.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

55

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.
Select: This algorithm uses Database trigger generated value as id value.
Hibernate software supplied some special built in tools to perform DDL operations on Database
software those are Create table, Alter table, Drop table operations.
Note: These operations are not possible through Hibernate 3.6.5
Built-in tools of Hibernate software to perform DDL operations:
1. SchemaExport(always creates new DB table)
2. SchemaUpdate(locates/create/alter Database table)
3. SchemaValidator(locates/validates the Database table)
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.
EX: java org.hibernate.tool./hbm2ddl.SchemaExport --config=hibernate1.cfg.xml (This is not
working in Hibernate 3.6.5)
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.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

56

To locate/create table:
1. Keep the first application setup as it is
2. Run the SchemaUpdate tool.
EX: java org.hibernate.tool./hbm2ddl.SchemaExport --config=hibernate1.cfg.xml (This is not
working in Hibernate 3.6.5)
To alter table:
1. Keep the first application ready
2. Add new property in EmpBean class having getter, setter method like String xyz
3. Configure this new property in hibernate mapping file.
4. Run the SchemaUpdate tool.
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.
Ex: java org.hibernate.tool./hbm2ddl.SchemaExport --config=hibernate1.cfg.xml (This is not
working in Hibernate 3.6.5)
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.
EX: java org.hibernate.tool./hbm2ddl.SchemaValidate --config=hibernate1.cfg.xml (This is not
working in Hibernate 3.6.5)
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.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

57

EX: <property name="hibernate.hbm2ddl.auto">create</property>
For Compete Program Please refer Hibernate execution\hbbmddl\Create folder
ii) Update(popular tool): Internally uses SchemaUpdate tool so that it can
locate/create/alter Database table. This value is most regularly used value.

EX: <property name="hibernate.hbm2ddl.auto">update</property>
In mapping flle:
<property name="Fname" column="FNAME" length="25" />
<property name="Lname" column="LNAME" length="22" not-null="true"/>
<property name="Email" column="EMAIL" length="21" unique="false"/>
For Compete Program please refer Hibernate execution\hbbmddl\Update folder
iii) Validate: If we keep any value it take as default value.
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:
INFO: columns: [lname, email, eid, fname]
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.
For complete program please refer Hibernate execution\hbbmddl\Validate folder
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.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

58

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.
i) Hibernate Software supplied buit-in pool
ii) Third party software supplied JDBC Connection pool.
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.
Procedure to work C3P0 JDBC Connection Pool in our Hibernate applicatios:
Step1: Keep first Hibernate application ready
Step2: Add C:\hibernate-distribution-3.6.5.Final\lib\optional\c3p0\c3p0-0.9.1.jar
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:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD
3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<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>
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

59

<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>
<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>
For Complete program please refer D:\Frameworks\Hibernate execution\C3P0 folder
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.
EX: like web applications, EJB components etc.,
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.
Gather information Step3 or Step4 from <hibernate_home>/project/etc/hibernate properties file.
Or Chapter 3.3 of pdf file. Run the Client application.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

60

Procedure to use Proxool Connection in Hibernate application:
i. Keep first application ready.
ii. Hibernate/lib/optional proxol/proxol-0.8.3.jar file to class path.
iii. Specify the connection provider class in Hibernate configuration file to work with
proxool tool.
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.,)
Run the Client application.
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.
For Complete Program Please refer Hibernate execution\Proxool folder.
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.
EX: Registry softwares.
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.

B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

61

Understanding the working environment of server managed JDBC Connection Pool:
Client Application webserver/Application server



















Returns JDBC Connection object back to JDBC Connection Pool

Gets JDBC
DataSource
reference from
Registry
Calls
getConnection
on DataSource
reference and
gets
Connection
object from
JDBC
Connection
Pool

Uses the
Connection
Object to create
other JDBC
Connection
object and to
develop JDBC
persistence
logic.




Con.close()

JDBC DataSource obj Server Managed JDBC
Connection
Pool

(for Oracle)





Uses Type-3/4 driver


Sathya(nick name for JNDI)
DataSource
10
5
6
8
2
3
7
1
4
9
8
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

62

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.
9,10) Refer diagram
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.
Q) How many Connections in JDBC?
A) Two types
1) Direct Connection using DriverManager.getConnection
EX: class.forName(..)
Connection con=DriverManager.getConnection(-,-)
2) Pooled Connection using DataSource.getConnection(). It is the JDBC Connection object that
is collected from JDBC Connection Pool.




B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

63

Web based Connection Pooling:
Web Logic Server:
Type: Application server
Vendor: BEA systems(Oracle)
Type of Software: Commercial software
Port number : 7001
Download: www.commerce.bea.com
Help related documents: www.edos.bea.com
Version: 8.1 jdk(out dated)
9.1-> jdk 1.5,1.6
10.0 -> jdk 1.7
Jar file: weblogic.jar
Note: weblogic9.1 supports jdk1.5,1.6 only not for 1.7
The multiple projects of Company uses multiple domains of web logic installing web logic
software only once domains will be created in the software.
Client Side Server Side









Java Application
JDBC Code
JDBC
driver for
Oracle
Oracle
Database
Software
N
e
t
w
o
r
k
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

64


Client Side ServerSide web Logic Registry





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
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.
InitialContextObject: It represents connectivity between Java application and Registry
software. To create this object we need JNDI properties will be change based on the naming
manager, Registry software we use. JNDI properties are like IntialContextFactory class name
provider url.
JNDI properties values of web logic registry:
IntialContextFactory class name: weblogic.jndi.WLInitialContextFactory(available in Web
Logic)
Provider url : t2://<host name>:<port no>t3://localhost
Procedure to use JDBC Connection Pool for Oracle created in Web Logic server in our
first Hibernate application:
1. Keep your first Hibernate application in running mode.
2. Keep the Hibernate domain server of Web Logic running mode.
3. Configure JDBC Connection Provider class to use server managed JDBC connection
pool in Hibernate application.


Java Application
JDBC Code
Naming
manager
for Web
LogicRe
gistry

N
e
t
w
o
r
k
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

65

In Hibernate.cfg.xml
<property
name="hibernate.connection.provider_class">org.hibernate.connection.DataSourceConnetionPro
vider</property>
4. Specify JNDI properties of Web Logic registration hibernate configuration file.
<property name="hibernate.jndi.class">WLInitialCotextFactory</property>
<property name="hibernate.jndi.url">t3://localhost:7001</property>
Specify JNDI name JDBC DataSource object in Hibernate configuration file.
<property name="hibernate.connection.datasource">sathya</property>
Add C:\bea\weblogic92\server\lib\weblogic.jar Web logic jar file to class path.
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.
For Complete Program Please refer D:\Frameworks\Hibernate execution\Weblogic folder
Connection PoolingGlass Fish:
Type: Application Server
Version: 3.1( Compatible with 1.6)
Vendor : Sum Microsystem(Oracle)
Registry Software: Glass Fish registry
Default Port nos: 4848 for admin console
: 8080 for accessing web applications
NetBeans IDE gives Glass Fish as built-in server we can use this Glass Fish wih or without Net
Beans IDE.
To download Net Beans IDE: www.netbeans.org
Glass Fish server allows creating domains.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

66

Default domain is : domain1
Procedure to create user defined domain server in Glass Fish:
C:\Program Files\glassfish-3.1.1\bin>asadmin create-domain --adminport 4545
Enter the value for the domain_name operand> testuser
Enter admin user name [Enter to accept default "admin" / no password]>
Enter the admin password [Enter to accept default of no password]>
Enter the admin password again>
Using port 4545 for Admin.
Using default port 8080 for HTTP Instance.
Using default port 7676 for JMS.
Using default port 3700 for IIOP.
Using default port 8181 for HTTP_SSL.
Using default port 3820 for IIOP_SSL.
Using default port 3920 for IIOP_MUTUALAUTH.
Using default port 8686 for JMX_ADMIN.
Using default port 6666 for OSGI_SHELL.
Using default port 9009 for JAVA_DEBUGGER.
Distinguished Name of the self-signed X.509 Server Certificate is:
[CN=bhargav-ae185c5,OU=GlassFish,O=Oracle Corporation,L=Santa Clara,ST
a,C=US]
Distinguished Name of the self-signed X.509 Server Certificate is:
[CN=bhargav-ae185c5-instance,OU=GlassFish,O=Oracle Corporation,L=Santa
California,C=US]
No domain initializers found, bypassing customization step
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

67

Domain testuser created.
Domain testuser admin port is 4545.
Domain testuser admin user is "testuser".
Command create-domain executed successfully.
Procedure to change the http port number the above domain to server:
Go to C:\Program Files\glassfish-3.1.1\glassfish\domains\domain2\config then select
domain.xml file and then search for following thing
<network-listener port="8080" protocol="http-listener-1" transport="tcp" name="http-listener-1"
thread-pool="http-thread-pool"></network-listener>
<network-listener port="8181" protocol="http-listener-2" transport="tcp" name="http-
listener-2" thread-pool="http-thread-pool"></network-listener>
<network-listener port="4848" protocol="admin-listener" transport="tcp" name="admin-
listener" thread-pool="admin-thread-pool"></network-listener>
Now change here
Procedure to open admin console of the above domain to server:
1. Start testuser server
C:\Program Files\glassfish-3.1.1\bin>asadmin start-domain testuser
Waiting for testuser to start ............................
Successfully started the domain : testuser
domain Location: C:\Program Files\glassfish-3.1.1\glassfish\domains\testuser
Log File: C:\Program Files\glassfish-3.1.1\glassfish\domains\testuser\logs\serve
r.log
Admin Port: 4545
Command start-domain executed successfully.
Open browser Type this url
http://localhost:4545
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

68



Stop the server:
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

69

C:\Program Files\glassfish-3.1.1\bin>asadmin stop-domain testuser
Waiting for the domain to stop
Command stop-domain executed successfully.
Note: User name and password of default domain
User name : domain1
Password : adminadmin
While writing hibernate persistence logic in different types of applications it is recommended to
create Hibernate Session object in one time. Use that object repeatedly to execute our program.
Where we have to create Session Object in Various technologies:
Application Componet Place to create Hibernate
session object
Place to use Hibernate
Session object.
Servlet Program

JSP Program





AWT Frame/SWING

Applet/JApplet

Struts


JSF


Spring Application


EJB 2.X


EJB 3.X


B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

70


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.
i) Keep Employee table ready
ii) Develop resource. That means write
One TestClient.java file, one EmpBean.java file, two mapping files( one for MySql another
for Oracle), two Configuration files.
MyCfg.ora.xml:
Same as first application
MyCfg.mysql.xml: same as initial applications pointing to MySql.
Employee.hbm.xml: Same as first application EmpBean.java
TestClient.java:
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class TestClient1
{
public static void main(String args[])
{
Session orases=new Configuration().configure(/mycfg-ora.xml).buildSessionFactory().openSession();
Session mysqlses=new Configuration().configure(/mycfg-mysql.xml);
buildSessionFactory.openSession();
//select a record from oracle Database
EmpBean eb=(EmpBean) orases..get(EmpBean.class,675);
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

71

System.out.println(eb.getNo+ +eb.getFame()+ +eb.getLname()+ +eb.getEmail());
//insert this record into mysql
Transaction tx=mysqlses.beginTransation();
Mysqlses.save(eb);
Tx.commit();
System.out.println(Record has been inserted successfully);
//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.
Servlet to Database communication by using Hibernate Persistence logic:
Jar files to classpath: servlet-api.jar, Hibrnate3.jar
Jar files in <WEB-INF>/lib:
Eight regular jar files.
Q) What is the Proxy object?
A) The object that represents temporarily presence of the real persistent state object is called
proxy object. Proxy object doesnt 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.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

72

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:
1. In Process of converting HQL queries to SQL queries performance will be degraded.
2. Using HQL queries PL/SQL programming is not possible.
SQL and HQL queries:
SQL> select * from employee;
HQL> from EmpBean(HB POJO class)
HQL> from EmpBean as e (e is alias name)
(or)
HQL> select eb from EmpBean as eb
(or)
HQL> from EmpBean
Note: as is optional every time.
SQL> select * from employee where fname like S%
HQL> select eb from EmpBean where eb.fname like S%
HQL> from EmpBean eb where eb.fname like S%

SQL> select fname, lname from employee
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

73

HQL> select eb.fname, eb.lname from EmpBean eb;
SQL> delete from employee where eid>=100 and eid<=200
HQL> delete from EmpBean as eb where eb.no<=200
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.

HQL queries are two types those are
1. Select Queries
2. Non Select Queries (use executeUpdate() to execute these queries)
Example of executing HQL query
For example applications please refer C:\Hibernate\HQL folder.
1. Keep first application setup ready.
2. Develop another client application having hibernate persistence logic.
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.
Executing the HQL select Query using iterate():
//prepare query by pointing HQL query.
Query q1=ses.createQuery(select eb from EmpBean eb);
Iterator ir=q1.iterate();
//makes Hibernate software to execute HQL query.
//process the results.
While(it.hasNext())
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

74

{
EmpBean eb=(EmpBean) it.next();
System.out.println(eb.getEid()+ +eb.getFname()+ +eb.getLname()+ +eb.getEmail());
}
System.out.println(it obj class name is +it.getClass());
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.

2. Generates single SQL select query.




3. Performs immediate initialization of
objects with selected records selected
table(indicates eagar loading)
4. EX: select four records from the table
which generates single SQL select
query.
5. Gives good performance
1. Select required records of the table
one after another.
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. Performing on demand initialization
of objects with records(indicates lazy
loading)
4. EX: To select four records from the
table it generates four SQL select
queries.
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.


B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

75


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.
HQL Parameters: HQL supports two types of parameters those are
i) Positional Parameters
ii) Named Parameters
Executing the HQL query with positional parameters:
Query q1=ses.createQuery("select eb from Employee eb where eid>? and eid<?");
//setting values to parameters
int a=100;
int b=200;
Integer a1=new Integer(a); //Object type casting
Integer b1=new Integer(b);
q1.setInteger(0,a1);
q1.setInteger(1,b1);
List l=q1.list();//make Hibernate Software to execute HQL query
//process the List DataSource
for(int i=0;i<l.size();i++)
{
ps.Employee eb=(ps.Employee)l.get(i);
System.out.println(eb.getEid()+" "+eb.getFname()+" "+eb.getLname()+" "+eb.getEmail());
System.out.println("object class name is "+l.getClass());
}
ses.close();
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

76


String based operation:
Query q1=ses.createQuery("select eb from Employee eb where eid>? and fname like ?");
//setting values to parameters
int a=100;
String b="M%";
Integer a1=new Integer(a); //Object type casting
String b1=new String(b);
q1.setInteger(0,a1);
q1.setString(1,b1);
List l=q1.list();//make Hibernate Software to execute HQL query
//process the List DataSource
for(int i=0;i<l.size();i++)
{
ps.Employee eb=(ps.Employee)l.get(i);
System.out.println(eb.getEid()+" "+eb.getFname()+" "+eb.getLname()+" "+eb.getEmail());
System.out.println("object class name is "+l.getClass());
}
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>)
Query q1=ses.createQuery("select eb from Employee eb where eb.eid>:P1 and eb.email like
:P2");
//setting values to parameters
int a=3;
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

77

String b="x%";
Integer a1=new Integer(a); //Object type casting
String b1=new String(b);
q1.setInteger("P1",a1);
q1.setString("P2",b1);

List l=q1.list();//make Hibernate Software to execute HQL query
//process the List DataSource
for(int i=0;i<l.size();i++)
{
ps.Employee eb=(ps.Employee)l.get(i);
System.out.println(eb.getEid()+" "+eb.getFname()+" "+eb.getLname()+" "+eb.getEmail());
}
Note: We can prepare HQL Query by having both positional and named parameters but we cant
define/place positional parameter after any named parameter have been defined/placed.
Positional Parameter before placing the Named Parameter.
Query q1=ses.createQuery("select eb from Employee eb where eb.eid> ? and eb.email like
:P2");
//setting values to parameters
int a=3;
String b="x%";
Integer a1=new Integer(a); //Object type casting
String b1=new String(b);
q1.setInteger(0,a1);
q1.setString("P2",b1);
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

78


List l=q1.list();//make Hibernate Software to execute HQL query
//process the List DataSource
for(int i=0;i<l.size();i++)
{
ps.Employee eb=(ps.Employee)l.get(i);
System.out.println(eb.getEid()+" "+eb.getFname()+" "+eb.getLname()+" "+eb.getEmail());
}
Invalid HQL query:
Because of we shouldnt 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 cant 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 ?");
HQL Select query with aggregate functions:
Query q1=ses.createQuery("select count(*) from Employee");
List l=q1.list();
Long l1=(Long)l.get(0);
long cnt=l1.longValue()
System.out.println("Cont of records"+cnt);
ses.close();




B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

79


//for complete program refer page no 50and Projects folder HQLTest project open
AggregateFunction

List Data structure





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

List Data Structure(i)








values of Collection Framework data structures. If we want to class name of certain dynamic
object call getClass() on that object.
Java.lang.long class object

Java.lang.Object.class.obj[]





0 1 2 3 4






Long Object Integer Object Integer Object Long Object Double

B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

80

Executing HQL select query with multiple aggregate functions:
Query q1=ses.createQuery("select count(*),max(eb.eid),min(eb.eid),sum(eb.eid),avg(eb.eid)
from Employee eb");
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);
System.out.println(" Average of records"+avg);
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

81

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:
Query q1=ses.createQuery("from Employee eb where eb.eid=(select max(eb.eid) from Employee
eb)");
List l=q1.list();
for(int i=0;i<l.size();i++)
{
Employee eb=(Employee)l.get(i);
System.out.println(eb.getEid()+" "+eb.getFname()+" "+eb.getLname()+"
"+eb.getEmail());
}
Getting each record from Table:
By using List
Query q1=ses.createQuery("select eb.fname,eb.lname from Employee eb where eb.eid>=?");
//set param values
q1.setInteger(0,10);
//execute HQL queries
List l=q1.list();
//process the results
for(int i=0;i<l.size();i++)
{
//access each element of the list
Object row[]=(Object[])l.get(i);
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

82

//process the elements of the list
for(int k=0;k<row.length;k++)
{
System.out.println(row[k].toString()+" "); //prints each record
}
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.
Executing above example based query with iterate():
By using iterate():
Query q1=ses.createQuery("select eb.fname,eb.lname from Employee eb where eb.eid>=?");
//set param values
q1.setInteger(0,10);
//execute HQL queries
Iterator itr=q1.iterate();
//process the results
while(itr.hasNext())
{
//access each element of the list
Object row[]=(Object[])itr.next();
//process the elements of the list
for(int k=0;k<row.length;k++)
{
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

83

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.
Update by using named Parameters:
Query q1=ses.createQuery("update Employee eb set eb.email='x@y.com' where eb.eid=:p1");
q1.setInteger("p1",10);
Transaction tx=ses.beginTransaction();
int result=q1.executeUpdate();
System.out.println("number of records affected"+result);
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.
Wrong HQL insert Query: insert into employee eb values(?,?,?)
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.
Example application to perform HQL insert query execution:
1. Create two tables in Oracle Employee and Employee1
Employee Same as first application
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

84

Employee1 same as Employee
Create two POJO classes Employee.java, same as first Employee1.java as first application
2. Create one mapping file configuring both Employee, Employee1 classes.
3. Develop single hb configuration(hibernate.cfg.xml)
4. Develop the client 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.
Limitations with following code:
Here HQL query is specific to one Hibernate Session object and it does not give global
visibility and flexibility of modification.
Example on named HQL Query:
1. Keep the first application setup ready
2. Place HQL query in Hibernate mapping file having logical name(as named as HQL
query)
Note: In one mapping file we can place number of HQL queries.
3. Write a logical client application to get access to named HQL query and to execute that
query by using multiple Session objects




B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

85

&lt: and &gt: 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 &lt: 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.
For complete program please refer Hibernate\Pagination folder
Procedure to develop custom algorithm which generates identity value in following
notation:
FF001
FF002



FF003
1. After the eid column data type to varchar2(10)
2. Create sequence in Oracle shown below
3. Create sequence1 increment by 1.
4. Keep first application ready.
5. Change number property data type to String in Employee.java (also change getSno,
setSno)
6. Copy SequenceGenerator.java file to first application folder from
Hibernate/project/src/main/java/org/hibernate/id folder
Rename the file name to FFGenerator.java
Rename the class name to FFGenerator
7. Do following modification in FFGenerator.java with respect to SequenceGenerator.java
file
a) Import following package import org.hiberate.id.*;
b) Write following code inside the definition of generate()
Refer line number 104-106
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

86

Public searializable generate(SessionImplementation session, Object obj)
{
return generateFolder(Session);
}
Make sure that following code is there in definition of generateHolder(-)
i) Change return type of the method2 String
ii) Make sure that following code is placed in the third try block
8. Configure above algorithm in Hibernate mapping file.
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.
For All Native SQL program please refer Hibernate
execution\NativeSQL\NamedNativeScalar folder
1. Native SQL queries are Database software dependent SQL queries.
2. Native SQL queries based persistence logic is Database software dependent.
3. Supports both select and non select operations.
4. Supports DDL operations.
5. Allows us to call PL/SQL procedures and functions.
6. Allows us to place both Named and Positional parameters.
7. SQL query object represents native SQL queries.
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.
Java type Hibernate JDBC
1. int
2. long
3. String
4. Double
Hibernate.INTEGER
Hibernate.LONG
Hibernate.STRING
Hibernate.DOUBLE
Types.INTEGER
Types.LONG
Tyes.VARCHAR
Types.DOUBLE
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

87






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.
EX: select * from employee
EX: select lname, fname from emp; e.t.c.,
Example application on an entity native SQL query execution:
1. Keep the setup of first application.
2. Develop the client application as shown below having topic of Native SQL query.
SQLQuery q1=ses.createSQLQuery("select * from Employee");
//make result with HB POJO Class
q1.addEntity(Employee.class);
//execute native SQL Query
List l=q1.list();
for(int i=0;i<l.size();i++)
{
Employee eb=(Employee)l.get(i);
System.out.println(eb.getEid()+" "+eb.getFname()+" "+eb.getLname()+"
"+eb.getEmail());
System.out.println("object class name is "+l.getClass());
}
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

88


Note: We cant iterate() to execute native SQL select queries when used
java.lang,UnSupportedException will be raised.
Executing Scalar Query:
In Employee.hbm.xml
<sql-query name="test1">
<return alias="test1" class="Employee"/>
SELECT * from Employee WHERE eid&gt;=?
</sql-query>
In TestClient.java
SQLQuery q1=ses.createSQLQuery("select fname,email from Employee");
//map Results with Hibernate Data types
q1.addScalar("fname", Hibernate.STRING);
q1.addScalar("email",Hibernate.STRING);
List l=q1.list();
for(int i=0;i<l.size();i++)
{
//access each element of the list
Object row[]=(Object[])l.get(i);
//process the elements of the list
for(int k=0;k<row.length;k++)
{
System.out.println(row[k].toString()+" "); //prints each record
}
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

89

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.
Executing named native SQL non-select Query:
1. Place query in mapping File.
<sql-query name="test1">
insert into Employee values(?,?,?,?)
</sql-query>

2. Access the query in the client applications and execute the query
//get access to Named Native SQL query
Query q1=ses.getNamedQuery("test1");
q1.setInteger(0,32);
q1.setString(1,"Tamanna");
q1.setString(2,"Bhatia");
q1.setString(3,"t@b.com");
Transaction tx=ses.beginTransaction();
int result=q1.executeUpdate();
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

90

System.out.println("number of records affected"+result);
Note: If we want to place hibernate.autocommit property in configuration file then we can
execute non select native SQL queries without transaction management code. Since this feature
is varying Database software to Database software. It is recommended to ignore feature.
We can perform DDL operations on Database using Native SQL queries but we cant 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.
1. When authentication logic is required in every module instead of writing the
authentication logic in every module it is recommended to centralized that logic by
keeping Database software only once as PL/SQL function or procedure.
2. In JDBC we use callable statement object to call PL/SQL procedure or function.
Hibernate 3 allows us to call PL/SQL procedure or function but procedure or function
must be developed as a required for Hibernate software for this we need to follow list of
rules. These rules will vary based on the Database software we use.
3. Cursor in Oracle is a variable that can hold set of records given by SQL select query
execution. The cursor of Oracle PL/SQL programming is same as the ResultSet object of
JDBC programming.
4. Oracle gives SYS_REF cursor as built-in default cursor type while developing PL/SQL
procedure or function in Oracle for hibernate we must work with cursors.
5. While developing SQL procedure or function in Database software for Hibernate we need
to follow set of common rules and set of Database software specific rules.
6. The common rules are
i) Pagination is not possible on the results of PL/SQL procedures and functions(we
cant use setFirstResult(-), setMaxResult(-))
ii) Standard Syntax(SQL92) should be used to call PL/SQL procedure or function.

To call procedure:
{call <procedure-name>(?,?,?-----)}
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

91

To call function:
{?=call<(function-name(?,?,?---)}
Oracle software specific rules:
PL/SQL procedure must have first parameter as OUT parameter having type (sys-ref cursor)
(or)
PL/SQL function must return a cursor (of type sys-ref cursor)


Machine2




Q) Difference between Remote and Local 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.
Limitations and Drawbacks of Hibernate:
1. Hibernate is not distributed technology. So its persistence logic cant 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 cant 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.
JVM


JVM2
JVM
Application LocalClient
Remote Client
Remote Client
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

92

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.
1. Criteria API persistence logic is Database independent logic.
2. Gives good performance compare to HQL.
Limitations:
1. We cant use Criteria API to select specific columns of a table.
2. We cant use Criteria API for non-select operations.
3. Working with Criteria API is complex process.
4. Criteria Object represents the Criteria API persistence logic. Criteria object means it is
the object of Java class that implements org.hibernate.Crieteria interface.
5. To create object for this we use Session.criteria(-).
Example application on Criteria API:
1. Keep setup of first application ready
2. Take separate client application and write following logic as the Criteria API based
persistence logic.

We can use various static methods of org.hibernate.Crieterian Restrictions, Expression class
to frame conditions required for the Criteria API based persistence logic. Each condition will
be represented criteria object. Entire API persistence logic will be developed based on HB
POJO class member variables.
Executing Criteria API logic with Condition:
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.
For complete programa please refer Hibernate execution\NetBeans Projects (This
folder will open with Net Beans 7.1 or higher versions automatically)
Q) what is the difference between Criteria object and Criterian Object?
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
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

93

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.
Expression.sql(-): It is depreciated from Hibernate 3.5 onwards and
Restrictions.sqlRestriction(-) has been given as an alternative
Criteria ct=ses.createCriteria(EmpBean.class);
Criteria cond=Restrictoins.sqlRestriction(email like %.com);
ct.add(cond);
List l=st.list();
for(-)
{
----
}
Versioning: Hibernate is capable of keeping the number of modifications done in records
through versioning. For this we need to maintain special co column in Database and special
property in Hibernate mapping file, POJO class. The feature helps banking applications how
many times the address or balance of Account holder has been changed during his yearly
transactions or monthly transactions that depends.
For Complete program please refer Hibernate execution\Versioning folder
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.
B. Siva Bhargava Reddy 8099498819 bhargavbsr@hotmail.com Nataraj Sir 11:00 am Batch

94

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.
For Complete Program Please refer D:\Frameworks\Hibernate execution\LargeObjects
folder
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
Procedure to develop Hibernate application having the utilization of Filters:
i. Keep first application ready.
ii. Define Filter having logical name and link that Filter with Hibernate POJO class
specifying mapping file.
In Mapping File:
1. Hibernate Filters are no way related to Servlet Filters.
2. If we need certain complex condition like getting tenth highest salary of Employee details
at that time multiple client applications are in multiple places of single client application
then instead of writing along with the query every time it is recommended to write only
for one time as Hibernate Filter condition in mapping file as shown above.
3. We can apply Hibernate Filters on the persistence logics of HQL Criteria API logics but
cant apply on persistence logics of Native SQL.
For complete program please refer Hibernate execution\Filters folder

You might also like