You are on page 1of 18

Hibernate :---

Hibernate is an ORM(Object Relationlal Mapping) tool

Enterprise: Its a Business organnisation or group of organisation running under a


single lable.

Enterprise Application : -- its a software application designed for an enterprise


in order to simplify their businerr processing.

To built the Enterprise application we have to provide the following layers

Presentation Layer
|
Business Processing Layer
|
Data Storage and Access Layer

1.Presentatoin Layer(user Interface layer) :----


i.its the topmost layer of enterprise application.It gives the Look and feel to
the enterprise application
ii.its the starting point of Users to interact with the enterprise applciation
iii. Provides good environment to get the data from users in order to execute the
enterprise application
iv. helps in doing client side validations using the javascript langugae
v.To prepare this layer we use separate logic called "presentation logic"
vi.To prepare this layer differennt technologies are used like AWT,Swing ,html,
JSP, javascript,velocity, Freemarker

2.Business Processing Layer


i.it is heart o business application
ii.provides the good environment to define and execute the business rules and
regulations required by the client
iii.To prepare this layer we woulld use separate logic called Business Logic
iv. Technologies like Servlets ,EJBs-session are used

3.Data Storage and Access Layer


i.Its the bottom most layer of enterprise applciation
ii.It provides data persistency in enterprise app. . i.e to interact with database
from java applciations to perform database operations.
iv. To use this layer we need separate logic called "Data persistance logic"
v. Technologies used are JDBC,Hibernate ,JPA, Toplick

DataPersistency :---
Represeting the data permanantely in Backend System is called Data persistency

1.To achieve this ,data base application use set of operations like [CRUD]
operations
C-Create ,R-Retrieve ,U-Update ,D-Delete
Tech used are w.r.t Java
1.Serialization and Deserialization
2.JDBC
3.ORM implementations
i.Hibernate
ii.EJBs Entity beans
iii.JPA
iv.Open JPA
v.Toplink

#Data Persistency through Serialization and deserialization


The processing eparating the Data from an Object is called Serialization
The process of regenerating the object from data is called Deserialization

#Serialization:---
--------------------
java Application
class Employee implements Serializable { |Employee empObj1=new Employee();|
ObjectOutputStream============Serialized Data===>---1010100(FileInputStream)---->|
File.txt |
int eno =100;
String ename ="aaa";
int esal =3;
}

|empObj2| <========(ObjectInputStream)=======<-------
10010100(FileInputStream)------| File.txt|
int eno =100;
String ename ="aaa";
int esal =3;

1.In serialization and deserialization ,we will store data in file system ,where
system is providing the permanent storage for our data.
2.In Ser,DeSer .. Two byte oriented streams are used ObjectOutputStream
,ObjectInputStream to perdorm serilaixation ,Deserialization .So that this data
persistency mechanism is possible fro only byte oriented data.
3.But its not suggestible to store data in file systems, due to security, data
redundandancy and less storage issues .
4.If we have to use data persistency mechanism in Entrprise apps. a lot of code is
required
5.In Data persistency mechanism, we are only able to perform store and retreival
process but not delete ,update operations.
6.Query language is not possible so database storage operations are not possible

Data persistency through JDBC


-------------------------------
To prepare JDBC application following steps are used
1.Load and register driver
Class.forName("com.jdbc.mysql.Driver");
2.Establish the Database Connection
Connection con = DriverManager.getConnection(url,username,password);
3.Create the Statement or PreaparedStatemnet object or callableStatemnet

4.write the sql query and execute

ResultSet rs = stmt.executeQuery(sqlQuery);

5.Close or release the resources


rs.close();
stmt.close();
con.close();
#########################################
IF we are ahving JDBC technology to interact wit Database why do we need
hubernate?????????

1.In JDBC we have to provide SQl queries explicitly to perform database


operations .So developers must require SQL database awareness.
2.In JDBC apps. Developers must need to explicitly establish or manage the Database
connection , Load and register Driver,Statement creation and executions .
3.Since Loading and registering the Driver , Database Connection
management,Creation and Excution of SQL queries are needed at manay parts of java
application so there is a problem of lot of Code duplication.
4.In JDBC we have to hardcode the JDBC connection parameters like URL ,username
,password
5.In JDBC ,Transaction support is not good
6.In JDBC all the exception are checked exceptions, so developer need to handle
them explicitly using try/catch
7.In JDBC ,if we retrieve data from Database in ResultSet object , as resultSet is
not implementing the Serializable interface so ,ResultSet objects are not able to
travel through network.

Hibernate Features :--


-------------------
1.its database independent i.e. it can be used with any DB (Mysql,Oracle,Postgress)
2.Its applciable for for Standalone and enterprise applications.
3.provides good support for Associations and Joins.
4.Its having good annotation support to reduce the XML dependency in enterprise
apps.
5.Its having good implementations for Primary key generation algorithms in order t
generate and insert a unique primary key value for each insertion into the DB
table.
6.It provides good support for Collections to manage the data.
7.hibernateh is having its own Query language which is database independent to
perform database operations.
8.It provides very good support to Cache mechanisms in order to resuse the results.
9.it provides very support of Connection Pooling in order to improve the database
connection reusablit.
10.Its supported by all IDEs and all Application servers.
11.hibernate is against SQL queries in enterprise applications directly,but if we
wanna write the Database dependent Sql Queries ,then its possible to provide the
database SQL queries using Native SQL.
12.Hibernate has provided very good support for Transactions.

Hibernate Config file will provide all config details like driver class
name,driver URL, DB username , password ,which are needed to create a DB
connection .
Hibernate Mapping file will provide mapping details like Bean class name mapped
to DB table name ,Properties mapped to Db tables Column.

1/Client Appl. will perform three actions in hibernate app.


2.Activate hibernate software,HB cosftware wil take care of all HB Config file and
Mapping file and HB software will setup a JDBC connection to do DB operations.
3.Prepare Persistance object with persistance data.
4.Perform persistance Operations.

HB software will perform following actions.


1.HB will take persistance method call and identify persistance Object.
2.HB software will take all mapping details from HB mapping file like DB table
name and all column names on basis of Persistance object.
3.HB software will prepare DB dependent sql query on the basis of table name and
all column names of Persistance object.
4.HB software will execute the generated database dependent sql query and perform
required persistance operation.

The main purpose of persistance object or class is manage persistance data which we
want to store in Db or by using this we want to perform Db operations like select,
update , insert

#Guidelines for persistance classes in HB:


1.In HB applications Persisitance classes must be POJO classes[Plain Old Java
Object ]They must not extend or implement any predefined library.
2.In HB apps. Persistance classes must be public(so that HB software can
acccess them within public scope for creation of their objects) , non-
abstract(for creation of persistance objects These classes must be non-abstract)
and non- final(to allow one persistance class to extend from one to other
persistance class when required)
3.In Persistance class all properties must be declared as per DB table
provided columns where names are not mandatory to match but data types must be
compatible.
4.In persistance class all properties must be declared private in order to
improve Encapsulation
5.In persistance class ,we must define setters and getters for each
property .
6.in Persistance classes all methods should be declared public.
7.In persistance classesz if we want to provide an y constructor , it must be
public and 0-ARG cobstructor ,Because while creating Persistance class object
HB software will only search for public and 0-Arg Constructor,
8.In HB software we will use POJO classes which dont extend or implementing
any predefined library but its suggestible to implement Serializable interface
for Serialazation and Deserialization of Persisstance classes objects.
9.

In HB app,mapping file is able tp provide mapping details like Basic OR mapping


,Component mapping,inheritance mapping,Collection mapping ,Associatioon mapping.
To prepare HB mapping file we have to provide mapping name as
POJO_CLASS_NAME.hbm.xml but this format is not mandatory we can use any name .
In HB software we can provide ay number of POJO clases ,w.r.t each and every POJO
class we can define separate Mapping file.

Note : Its possible to configure more than a single POJO class in single mapping
file

Hibernate Mapping File: --


----------------------------
1.<hibernate-mapping> tag is used in mapping file.it will include number of
classes configuration.
2.<class> tag is used to provide single pojo class configuration inorder to
provide mapping b/w POJO class name and repective table name.
3.name attribute is used to provide fully qualified name of POJO class.
4.table attribute is used to provide the DB table name in Class tag
5. <id> tag is used to provide ID properly configuration in order to provide
mapping b/w ID property and respective primary key column.

Note: -- if bean property name and column name are same then its optional to
provide the column attribute in mapping file.

<!DOCTYPE...>
<hibernate-property>
<class name="POJOCLASS" table ="tablename">
<id name="id" column="eno"/>
<property name="ename"/>
<property name="esal" column="emp_sal" />
<property name="eaddress" column="emp_address"/>
</class>
</hibernate-property>

2.Prepare HB Configuration file:


The main purpose of HB configuration file is to provide the major configuration
details of HB application including JDBC parameters required to establish JDC
connection .Cache mechanism configuration.Connection pooling config.

In HB application ,the standard name of HB file should be hibernate.cfg.xml ,its


not mandatory to use only this name.
In HB app. we are able to provide only one Condiguration file,But if we use
multiple Databases we need to prepare HB configuration file for respective
Databse.

To prepare HB configuration file we must use following XML tags:---

hibernate.cfg.xml

<!DOCTYPE ...">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">@Raman@Ladda@100</property>
<property name="hibernate.connection.pool_size">10</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL57Dialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<mapping resource="Account.hbm.xml"/>
</session-factory>
</hibernate-configuration>
1.<hibernate-configuration> tag is the root tag
2.<session-factory> tag is used to include HB properties Configuration
3.<property> ttag is used ot provide single property config.
4."name" attribute is used to provide property name and body of <property > tag
will take a property value.
5.<mapping> tag provide mapping file config.
6."resource" attribute is used to provide mapping file name and location

In HB Configuration ,"dialect" property is to provide dialect class name.Its


providing respective database native implementation which are used in HB app. in
order to ptovide DB dependent sql queries by HB software.

HB has provided various dialect classes as


org.hibernate.dialect.XXXXDialect for each Database

4.Prepare Clinet APplication :---


The major task of HB app. is to activate HB software and create persistaance
objects and perform persisyance operations.

Following are steps to implements HB app.

1.create HB Configuration class object.


2.create session factory object.
3.create session object.
4.crreate Transaction object if required.
5.Perform persistance operation
6.close session Factory and Session obejcts

HB Config file : ----


public Configuration configure();
meyhod will fecth the configuration details from config
file(hibernate.hbm.xml) if this file doesnt exists then FileNotFoundException
occurs.
2.public Configuration configure(String file_name);
imeyhod will fecth the configuration details from config
file(hibernate.hbm.xml)
3.public Configuration configure(File fileObject ) meyhod will fecth the
configuration details from config file(hibernate.hbm.xml) using the File class
Object;
4.public Configuration configure(URL url)
the method used to access the Configuration file from java.net.URL the file
is available in network
5.Configuration cfg= new Configuration();
cfg.confgure();
when we use the configure method ,HB software will load the hibernate.cfg.xml
file in memory.if this file is available then it will load the content of the
file.

2.Create SessionFactory Object :


In HB the main reason of using the SessionFcatory Objejct is to manage the Db
Connections ,statements ,Cache levels and a number of Hibernate Session Objects

To obtains the SessionFactory Obejct , we have interface


"org.hibernate.SessionFcatory"

To get SessionFactory object we have to use following methid from Configuration


Class

public SessionFactory buildSessionFactory();


e.g. SessionFactory sfactory = cfg.buildSessionFactory();

Note:- The above approach to get SessionFactory object was used till
Hibernate3.x ,its deprecated in Hibernate4.x

In HB applications ,if we use multiple Databases then we habe to prepare


multiple Configuration files ,mutliple Coniguration object w.r.t this, we have to
prepare multiple SessionFactory objects.

SessionFactory object is heavy weight obejcts and it is thread safe upto


particular database ,beacuase ,it is able to allow multiple thread at a time.

3.Create Session object:

1.In HB ,for each and every Database interaction Session object is created
2.In HB ,Session object is able to provide number of persistance methods to
perform persistance operations
3.To represent Session Object Hb has provided predefined interface in form of
"org.hibernate.Session"

To get Session object we have to use following method of Sessionfcatory


interface

public Session openSession();


e.g. Session session = sessionFcatory.openSession();

In HB Session Object is light weight but not thread safe , because for each
and every thread a new Session objec is created.

4.Create Transaction Object: --


Transaction is a unit of work performed by Frontend System on BackEndSystems, To
represent Tranasctoins ,HB has provided interface "org.hibernate.Transaction"

To get Trasnaction object we can use folllwoing method :


1. public Transaction getTransaction();

it will return Transaction object without beginning txn , For starting txn ,we
can use
public void begin();

2. public Tranasction beginTransaction()


It will return and begin transaction();

In HB, for performing the Persistance operation we must either commit or


rollback the operation , For this we have following methods in Session interface

public void commit()


public void rollback();

NOTE:- In HB ,Transaction object is required for only Non select statements


not for Select Statements.
Difference b/e save(Object) and persist(Object);
Ans:-int save(Object) ; method returns primary key of column inserted
void persist(Object); method returns nothing

Hibernate persistence Object Lifecycle:--

The collective information of hibernate Object right from beginning to end is


called Persistence object lifecycle.

When we create hibernate Pojo object following are the states of object:--
---------------------------------
1.Transient state
2.Persistence state
3.Detached state
4.Removed state

1.Transient State:--
i when we create HB object then automatically POJO object will come into
transient state.
ii.If POJO object is in transient state ,then HB is not aware of the POJO
object.
iii.If POJO Object is present in Transien state ,then it is representing any
record in Database.
iv. In this state ,HB is not able to provide synchronization b/w POJO object and
record in database.
v.In this state if we perform any modification in POJO object then that
modifications are not reflected in Database.
vi.If we keep POJO object in Transient state for long time ,then it will
become eligible for Garbage Collection and GC will destroy it after its scope
is over.

Persistence State:--
i.It will peerform the operations like save () , saveOrUpdate() , update()
....over POJO object which is available in transient state.
ii.In HB app. if we perform operations like get() , laod() , find() ,
automaticaly HB will create object in persistence state directly without
Transient state.
iii. In Peersistance state the HB is aware of the POJO object and database
table record and its synchronization .
iv. In persistance state , if we perform any modifications in POJO object then
that modifications are reflected in Database table record .

3.Detached state:--
i.If we preform any operations like close() , clear() , evict() ,over the
session object then POJO object will come from persistance state to Detached
state
ii. In Detached state , HB is not aware of the POJO object and it will not
provide the synchrnization b/w POJO object and database table record.

iii.In detached state, POJO obejct is representing a valid record in database


table but modifications in POJO Object will not be reflected in DB record.
iv. In detached state , if we perform operations like save() ,update() ,
saveOrUpdate() over the persistance object t after getting session back
then POJO object will transfer from Detached state to persistance state.
v . If we keep POJO obejct in detached state for along time ,then GC will
colllect it destroy it.

4.Removed State:--

i.If we perform operations like remove() , delete() over POJO object in


persistance object then POJO object will come from persistance state to
Removed state.
ii. In removed state ,HB is not aware of the POJO object.
iii. In Removed state POJO object is ot representing any record in Database
table.
iv. If the POJO comes to Removed state , then its not possible to bring that
object back to persistance state directly .it must be garbage collected.

Example :--
-----------
Employee emp = new Employee() //Transient state
-----
session.save(emp)//persistance state
---

------
session.delete(emp) //removed state

session.close();//detached state

In Hibernnate app. To perform operations like insert ,update ,delete ,we can
use methods like save() , update() , delete() from org.hiebrnate.Session
interface provided by HB soft.

1.SchemaExport :-
This tool is provided by Hibernate soft. in the form of
org.hibernate.tool.hbm2ddl.SchemaExport predefined class in hibernate3.jar file.

If we activate above tool then it will perform the following actions.


a. First SchemaExport toool will take name and location of hibernate
Configuration file which we have provided as input parameter.
b. SchemaExport tool will load and parse hibernate configuration file.
c.SchemaExport tool will recognize mapping file configuration file then it will
load and parse the mapping file.
d.As per mapping file details , SchemaExport tool will whether any table
existed or not in Database.
e.If no table is existed then SchemaExport tool will create the new table as
per mapping file details.
f.If the table is existed with the name the SchemaExport will drop that
existed table and create the new table as per mapping file configuration
file.
To activate the SchemaExport tool manually through command prompt then we
have to use the following command .

D:\apps>java org.hibernate.tool.hbm2ddl.SchemaExport --config=hibernate.cfg.xml

Note: all mapping , configuration ,files must be at same place where this
schema is being activated.

In HB app. we are able to activate SchemaExport and SchemaUpdate . tools in


declarattive manner also .for this we have to use property in hibernate
configuration file.
hibernate.hbm2ddl.auto
The above property will take the following three values.
1.create
2.update
3.create-drop

1.create : this option for "hibernate.hbm2ddl.auto" property will activate


SchemaExport tool. it will create the table irrespective of the table is
existed or not.
ex.
<hibernate-configuration>
--
<property name="hibernate.hbm2ddl.auto">create</property>
--
</hibernate-configuration>

2.Update : this option for hibernate.hm2ddl.auto" property will activate


ScheamUpdate tool.it will create the table if not existed ,it will alter the
table if table is existed as per the mapping file. it will not delete the
removed columns but add new columns.
ex.
<hibernate-configuration>
--
<property name="hibernate.hbm2ddl.auto">update</property>
--
</hibernate-configuration>

3.Create - drop : -- this option for " "hibernate.hbm2ddl.auto" property


will create the table when SessionFactory object is created and it will
drop the table when SessionFactory object is destroyed

<hibernate-configuration>
--
<property name="hibernate.hbm2ddl.auto">create-drop</property>
--
</hibernate-configuration>

Primary Key Generation Algorithms in hibernate:--

1.Primary key is a single column or collection of columns in a table to


recognise the records individuallly ..
2. In DB app. to perform the DB operation like retreiving a record , deleting
, we need primary key and its value.
3. In Hibernate DB , we cannot give option to user for entering the primary
key so we need hibernate to manage that as there no gurrantee of data entered
by user whether its unique or not.
4.To give uniqueness to primary key , we have to use primary key algorithms.
5.Almost all the persistence mechanisms like JPA, Hibernate, Open JPA, Toplink
,, are having their own implementation for Primary key generation algos.

Hibernate has represented all the primary key generation algos. in the form of
a set of predefined classes provided in

"org.hibernate.id" package.

if we wanna use any of the primary key generation algos in HB app. we have
to configure that algo. in hibernate mapping file by using following tags,

<hibernate-mapping>
<class name=" .." table=".." >
<id name=".." column=".." >
<generator class="..">
<param name=".." > value</param>
</generator>
</id>
</class>
</hibernate-mapping>

where <generator> tag will represent a particular primary key generation


algo.
where "class" attribute in <generator> tag will take either short name or
fully qualified name of generator class .
where <param> tag will provide the single input parameter to primary key
generator inorder to generate the key value.
where "name" in <param> tag will take paramter name , here we have to
provide the parameter value as body to the <param > tag.

Assigned:--
----------
1.its default primary key generation algo. in HB app. it doesnt require any
configuration in HB mapping file.
2.It doesnt have its own mechanism of primary key generation , rather it
requires user to enter the primary key value explicitly
3.it supports various primary key values of int, short , long, String

4.It is supported by all Dbs like Oracle ,Mysql ,DB2


5.Its does not require any i/p parameter value .
6.This algo is represented by HB in the form of predefined class
"org.hibernate.id.Assigned"

<class name="className" table="tablename">


<id name="eno" column="ENO">
<generator class="assigned"/> /*either u can give short name or fully
qualified name = org.hibernate.id.Assigned*/
</class>
Increment:--
----------
1.This primary key generation algo. si able to generate primary key value by
incrementing max value of the primary key column.
New Value= max(PK_Column) +1

2. This algo. ia able to generate the primary key of data types of data type
short , int , long.

3.It doesnt require any input parameter to generate the primary key values.
4.This algo. supported by most of DBs which are supoorting numeric values as
primary key values.
5.This algo is represented by HB in form of short name "incerement" ans in
form of a predefined class "org.hibenrate.id.IncrementGenerator"

ex:-
<hibernate-mapping>
<class name="classname" table="tablename">
<id name="eno" column="emp1">
<generator class="org.hibernate.id.IncrementGenerator">
</id>
</class>
</hibernate-mapping>

3.Sequence:--
---------------
1.This primary key generation algo. is able to generate primary key value on
basis of the sequence provided the underlying Db.
2.This algo is able to generate primary key values of the data types like
short , int , long .This algo. required "sequence" input parameter with the
sequence name as value inorder to generate primary key value.
3.If we have not provided any sequence name as input parameter then this
algo is able to take "hibernate_sequence" as default sequence name.here
devvelopers must create "hibernate_sequence" in database explicitly.

This algo. is supported by almost all the databases which are supporting
sequences like Oracle ,DB2.
:
This algo. is represented by HB software in the form of short name like
"sequqnce" and in form of a predefined class like
"org.hibernate.id.SequenceGenerator".
ex.
In DB
SQL>create sequqnce ny_sequqnce increment by 5;"
SQL>commit;

In mapping file:
<hibernate-mapping>
<class name="classname" table="emp1">
<id name="eno" column="ENO" />
<generator class="sequqnce" >
<param name="" >my_sequqnce</param>
</generator>
</id>
</class>
</hibernate-mapping>
4.Identity:--
-----------------
This algo is able to generate the primary key value on the basis of
underlying database table provided bby identity column.

Note: Identity column is a primary key column with "AUTO_INCREMENT"


capability.

This algo is able to provide the primary key values of the data types like
int ,short , long.

This algo is not required any input parameter.


This algo. is supported by almost all DBs which are supportung identity
column.
ex. Mysql.

Represented by "identity" or "org.hibernate.id.IdentityGenerator" as predefined


class.

5.(hilo) High-Low
--------------------

This algo is able to generate the primary key value by getting high value
from a particular global resource and low value from mapping file.

Note:-- Global resource is particular table with a column in the same DB.
This algo is able to produce primary key values of the data types like short
,int ,long..

Represented by "hilo" or "org.hibernate.id.TableHiloGenerator"

Global resource :- Table in Db.

Supported by Mysql , Oracle,


Following parameters are used to generate the primary key values.
1.table :- Global resource name i.e. a table name which provides high value.
2.column:- column name existed in Global resource to geive high value.
3.max_lo : - it will provide the low value.

ex.
<hibernate-mapping>
<class name="Employee" table="emp1">
<id name="eno" column="ENO" />
<generator class="hilo" >
<param name="table" >my_table</param>
<param name="column" >my_column</param>
<param name="max_lo" >10</param>
</generator>
</id>
</class>
</hibernate-mapping>

In Db:--
SQL> create table my_table(my_column int(11) primary key);
SQL> insert into my_table values(100);
SQL> commmit;

6.Sequence-Hilo:--

1.This algo works by generating prumary keys values on the basis of sequence
value provided by the underlying database and the mapping file provided
max_lo property value.
2.This algo is almost same as HILO but here sequence value is used
inplace of high value from global resource.
3.This algo is able to generate primary keys of type int, short ,long.
4.This algo is represented by Hibernate software in short form of "seqhilo"
and the predefined class name as "org.hibernate.id.SequenceHiloGeneratr".
5.This algo is supported by all DBs which are supporting sequence internally.
6.This algo. requires following two input parameters.

1.sequence : it will take sequence name provided by DB.


2.max_lo : it will provide low value.
NOTEL:-- if we dont provide dequence paramter then HB wil search for default
sequence with name "hibernate_sequence" .

<hibernate-mapping>
<class name="Employee" table="emp1">
<id name="eno" column="ENO" />
<generator class="seqhilo" >
<param name="sequence" >my_sequence</param>
<param name="max_lo" >10</param>
</generator>
</id>
</class>
</hibernate-mapping>

7.Native:---

1.This algo . is able to generate primary key value by selecting a


particular primary key generation algo. depending on Db which we used.
2.This algo is not having its own algo. to generate primary keys .It will
select "SequenceGenerator" algo. if we are using Oracle Db. "IdentityGenerator"
algo. if we are using, Mysql Db. and "TableGenerator" if we are using some
other Db which is not using "SequenceGenerator" and "IdentityGenerator"
3.The primarry key generator is able to generate the value of type short,
int ,long.
4.the primary key generator is supported by almost all DBs.
5.To represent this algo, Hb has provided a short name in the form of
"native" .HB has not provided any predefined class.
6.This algo is able to take paramteres on the basis of selected primary key
generator depending on the DB. If its using "SequenceGenerator" then we must
provide "sequencce" parameter . If its using "TableHiloGenerator" then we must
provide the "table" , "column" , "max_lo" parameters.

<hibernate-mapping>
<class name="Employee" table="emp1">
<id name="eno" column="ENO" />
<generator class="native" >
----------------provide paramters depending on requirement------------------
<param name="sequence" >my_sequence</param>
</generator>
</id>
</class>
</hibernate-mapping>

8.select :--
1.This algo is able to generate primary keys on the basis of underlying DB
provided triggers.
2.This algo . is able to provide primary key values of the data types like
short ,int ,long.
3. This algo. is represented by HB software in the form of a short name like
"select" and a predefined class name "org.hibernate.id.SelectGenerator".
4.This algo. may take input parameter which are related to triggers..
5.this algo is supperted by all Dbs which are supporting triggers.

<hibernate-mapping>
<class name="Employee" table="emp1">
<id name="eno" column="ENO" />
<generator class="select" >
----------------provide paramters depending on triggers------------------
<param name="trigger" >trigger_name</param>
</generator>
</id>
</class>
</hibernate-mapping>

9.UUID (Universal Unique Identity)


1.This algo is able to generate primary key values based on the System IP
Address ,JVM, Startup time ,Current Ssytem time factors.
2.This algo is able to generate primary key value in form of 32 bit hexa decimal
value.
3.This algo. is able to generate primary keys of type String data type.
4.This algo is represented by HB in short form of "uuid" and by predefiend
class "org.hibernate.id.UUIDHexGenerator" .
5.This algo is suported by almmost all DBs which are supportiung string type
key values.
6.This algo does not need any input paramters but the primary key table
column must be of varchar type with minimum 32 bit column size in DB column.

<hibernate-mapping>
<class name="Employee" table="emp1">
<id name="eno" column="ENO" type="string"/>
<generator class="org.hibernate.id.UUIDHexGenerator" >
</generator>
</id>
</class>
</hibernate-mapping>

10.GUID : --
1.This algo is used to generate the primary keys on the basis of underlying
database provided identity column with String type.
2.This algo is represented in the form of a predefined class
"org.hibernate.id.GUIDGenerator" and in the short name like "guid".
3.This algo doesnt need any input parameters for generating primary keys.
4.This alo is suppported by DBs which are supporting String type id
columns.

<hibernate-mapping>
<class name="Employee" table="emp1">
<id name="eno" column="ENO" type="string"/>
<generator class="org.hibernate.id.GUIDGenerator" >
</generator>
</id>
</class>
</hibernate-mapping>

11.Foreign :----
1.This algo is used to generate primary keys on the basis of foreign keys of
the present table.
2.generates Short ,int , long type primary keys
3.Its doesnt require any input parameters .
4.Represented in short form of "foreign" and in the form of predefined
class as "org.hibernnate.id.ForeignGenerator"

<hibernate-mapping>
<class name="Employee" table="emp1">
<id name="eno" column="ENO" type="string"/>
<generator class="org.hibernate.id.ForeignGenerator" >
</generator>
</id>
</class>
</hibernate-mapping>

--------------------------------------------------------------
Annotations Support for Primary Key Generation Algorithm
--------------------------------------------------------------

use
@Id
@GeneratedValue(strategy =GeneratedValue.SEQUENCE))

1. HQL
HQL is query language provided by Hibernate inorder to perform
manupulations pver multiple records.
HQL is object oriented query language. it supports object oriented
features like encapsulation , polymorphism. but SQl is structure query
language.
HQL is DB dependent independent language, but SQL is DB dependent query
language.
In HQL we will prepare queries using POJO class names and their
propertires names but in SQL we will prepare queries on basis of DB table
names and table columns.
HQL queries are prepared by using syntaxes which are similar yo SQL
query language.
HQL is mailny for retreival operation but from HB 3.x version we can
use HQL to perform insert ,update, and delete opertions with select operation
but SQL is able allow any type of DB operations..
In case of JDBC , SQL if we execute the Select query then records are
retreived from DB table and stored in form ResultSet object which is not
implementing Serializable interfavce so its not possible to transfer in the
network but in case of HQL , if we retrieve records then that records
will be stored in Collection object whic is serializable bydefault , so that
we are able to carry objects through network.

HQL is databsee independent query language , but SQL is database dependent


query language.

In case of Hibenrate apps . if process any HQL , query then HB software


will convert that HQL. Query into databse SQl.
HQL cannot be used where there are database dependent queries

.Ex. PL/SQL procedures and functions are totally database dependent queries
so HQL cannt be used.

1.Represent the HQL query by creating Query object.


Query object is able to store HQL query . to represent Query object
HIbernate has provided a predefined interface in form of
org.Hibernate.Query
eg. Query q= session.createQuery("from Employee");
Apply custom properties on HQL Query , ohn Query object.
set custom pops. like fetch size , making results as Cache reslults and
read only.

1.public void setFetchSize(int size);;


2.public void setCacheable(boolean b);;
3.public void setMaxResults(int value);
4.1.public void setFirstResult(int size);
1.public void setReadOnly(int size);
1.public void setCommednt(String comment);;
1.public void setTimeOut(int size);;

----------------

public ScrollableResults scroll();

ScrollableResult
public boolean next();
public void first();
public void last();
public void previous();
public Object get(int position);

4.public Object uniqueResult();


Query q = sesion.createQuery("from Employee where empid =111 ");
Object obj = q.uniqueResult();
Employee e = (Employee) obj;

5.public int executeUpdate();

Query q = session.createQuery("update Emplpoyee set esal = esal + 500 where


esal <1000");
transaction tx = session.beginTransactoin();
int rowcount = query.executeUpdate();
tx.commit();
tx.close();

You might also like