Hibernate Material
Hibernate Material
DURGASOFT
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
1
HIBERNATE
Syllabus:
Hibernate Architecture.
Introduction to IDE.
<generator> element.
Inheritance mapping
• Criteria Query.
• Named Query.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
2
JAVA Means
DURGASOFT
• Relationships in Hibernate.
o One to One
o One to Many
o Many to One
o Many to Many
Hibernate Annotations.
Notes:
Hibernate Framework
About Developers:
Hibernate was started in 2001 by Gavin King with colleagues from Cirrus
Technologies as an alternative to using EJB2-style entity beans. Its original goal
was to offer better persistence capabilities than offered by EJB2 by simplifying
the complexities and supplementing missing features.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
3
JAVA Means DURGASOFT
Hibernate ORM
For making DAO classes in industry they used to depends on EJB entity beans+jdbc
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
4
JAVA Means DURGASOFT
Futures of Hibernate ?
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
5
JAVA Means DURGASOFT
Usually for making enterprise applications software industry will fallowsMVC rules. As
per MVC Application should divide into 3sub layers
For making Abstraction On each layer they will put Interfaces on top of their
Implementations
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
6
JAVA Means DURGASOFT
Model Objects
N
i. Read data
E from form
i. Business operations
A ii. send to
Dao operations
ii. cal Data
using hibernate
Presentati Access Layer for DB
operations DAO
on Layer
Controller(servlet) Business Layer
Hibernate Architecture
ModelObjects
HibernateFactory Configurations
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
7
JAVA Means DURGASOFT
Save(){
DB1 DB2 DB3
}update(){
Ex:Oracle Ex:MySql EX:IBM DB2…
}delete(){
}Select(){
el Object:
ll store data(state) in Objects state before moving object into database state .
ll store data into objects state while selecting data from database
h the files we have the following draw backs:-
s are very complex to work.The programmer must know atleast one programming language ,in order to work with file
s does not support Query language.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
8
JAVA Means
DURGASOFT
5)In order to overcome the draw back of File manage ment System.we entered
into DataBase ManageMent System(DBMS).
DrawBacks of Jdbc
1) In jdbc ,if we open a database connection then,we are responsible to close it.if
the connection is not closed, later there is a chance of getting out of connection
problem.
2)In jdbc,we write SQL commands at various places in the programe.after the
programe has to created,if the lable structure or designe is modified then the jdbc
programe does not work.in order to work it,we need to go to the each place of sql
command and we need modify according to the new designe.
5)In order to over come the above problems, Sun Micro System provided Entity Beans
in in J2EE.
EntityBeans:-
1) Entity Beans are the persistant components given under EJB technology(Enterprise
Java Beans).
2)In order to overcome the draw backs of JDBC technology given under J2SE or JSE
,Sun micro Systems introduced Entity beans under J2EE or JEE.
4) Entity Beans are introduced,in order to too and fro the data b/w a java
application and db,in the form of objects.
9 DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
10
DrawBacks of Entity Beans:
Entity Beans only run on a middle were server.so additionally we need to install a
middle were server in a system.
shutdown the server and later we need to restart the servr. Until the server is going to shutdown and until t
Hibernate is not saying that our class extends of class that way hibernate is called non-
invasive
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
11
JAVA Means DURGASOFT
5) Invasive Fw means,it will force the programmer to implement (or) extends their
class
s class (or) interface that is given by Framework.
e can be use either standalone app, servlet (or) spring any wre can be run. We can not writ any b.l in hibern
{ {
------------------ -----------------
Hibernate hibernate
}
So hibernate can be run inside server and outside
NOTE:- Hibernate runs with in a server and even with out a server . it means
hibernate is suitable for all types of java applications.
12 DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
JAVA Means DURGASOFT
We can us hibernate for standalone applications and in web application and also in an
enterprise application.
Hibernate is tool, used for implementing persistence logic for the real time
applications.
Q).why mapping?
dentity (name)
State (values)
Behaviour (methods)
But, while Storing an object in a dbase, only values can be stored. It is not possible to store identity and beha
n order to inform what value of an object should be stored in what column of table, mapping is required
NOTE:-Mapping can be done using two way 1) using xml 2) using annotations.
ADVANTAGE OF JDBC:-
i) Hibernate when you saved derived class object, then automatically the
base class data also inserted in db. It means in hibernate we got inheritance
support.
ii) Hibernate support relation ships like one to many, many-to-one,one-to-one
and many-to-many
iii) Hibernate support the collections like list, set and map
ii) if all exceptions are unchecked exception, the we no need write , try,
catch, and throws exception. While writing hibernate code.
5) If the database Scheme does not exit then only it will insert th data
otherwise throws an exception (lable (or) View does not exit)
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
14
JAVA Means DURGASOFT
6) Hibernate supports coaching mechanism by this, the number of round trips b/w
an application and a dbase will be reduced.
7) Hibernate support coaching mechanism by this, the number of round trips b/w
an application and a dbase will be reduced.
NOTE:-in hibernate, we have one draw back called, hibernate does not support
distributed transactions.
ii) in order to overcome the drawback of hibernate JBOSS (Soft tree original name)
communicative realses an extension of hibernate called Hibernate hards.
1) Pojo Class.
2) Mapping Xml (<anyname >.hbm.xml)
3) Configuration xml (<anyname >. Cfg.xml)
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
15
JAVA Means DURGASOFT
POJO CLASS:-Pojo class means no need to extends from any java class (or) implement
any interface
ii) this Pojo class contains private properties variable and for each property a
setter and getter method.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
16
JAVA Means DURGASOFT
Return customerid;
…………
………..
ILE:- <hibernate-mapping>
customer” table=”customer”>
stomerid” colume=”custid”>
= custname” column= “ customer”> This file is an heart of an hibernate application Every ORM tool needs t
echanism of placing an object properties into columns of a table.
be given to an ORM tool either in the form of an xml (or) in the form of
annotations
The mapping file contains mapping from a pojo class name for a table name and
pojo class variable names to table columns names.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
17
JAVA Means DURGASOFT
While columns an hibernate application , we can construct one (or) more mapping
files.
SYNTAX:-
<anyname>.hbm.xml
<id name =” Variable name “ column ”column name” type = javatype/hibernate type”>
</id>
…………………
…………………
</class>
</hibernate .mapping>
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
18
JAVA Means DURGASOFT
Even through a table does not have any p.k but in the mapping file id element is
mn of the table can be mapped as id Property element represent non-primary key mapping.
we need to specify a generator class name it inform of hibernate how the primary key value for the object is
if u want to write more than once and we need write the class for more than once.
EXAMPLE: <Hibernate-maping>
………………
……………...
</class>
<class name “ “table”>
…………..
………….
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
19
JAVA Means
DURGASOFT
</class>
</hibernate.mapping>
Configuration file:-
1) Connection properties.
properties.
names.
file loaded into hibernate application when working with hibernate this configuration file contain 3 types of in
on properties. 2)hibernate properties.
g files.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
20
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
21
We need create one configuration file for each db separately
In hibernate the configuration can be provided by creating either properties file (or) an
m of a resource bundle(properties file) but in hibernate 3.x, the resource bundle is replace with an xml file, bu
file is required
Syntax:
<anynam>.cfg.ml
<!..DTD/Schem is must..>
<hibernate-configuration>
<session-factory>
<!—connection properties
Driverclassname </properly>
<properly name=”hibernate.connection.url</properly>
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
22
JAVA Means DURGASOFT
<properly name=”hibernate.connection.username”>username</prop>
<properly name=”hibernate.connection.password”>password</properly>
<!—hibernate properties
<properly name=”hibernate.hbmaddl.auto”>create/update</properly>
……………..
……………..
</session –factory>
</hibernate –configuration>
While constructing this configuration file, we need to provide either connection
properties (or) JNDI properties in order to get a connection with the database.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
23
JAVA Means DURGASOFT
In general we write configure file name is hibernate cfg.xml but is not mandatory
to write the configuration file name as hibernate.cfg.xml instated we can put any
name
NOTE: hibernate is java based middleware, for transferring the data in the form of
objects b/w a java application and a Dbase server
d in a java application, that is going to run either with in server (or) out side a server, but weaneed to follow th
ibernate we do not required any server software
d hibernate s/w (jar files of hibernate)
hibernate.cfg.x; Package.
24 DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
JAVA Means DURGASOFT
Whenever configuration file is loaded into a java application then we can say that
hibernate environment is started this step is also called as boot strapping hibernate
into a java application.
gure(“hibernate.cfg.xml”);
ctory is an interface and sessionFactory.xml is an implemented class and both are given in org. hibernate.*
get an object of sessionFactory, we need to call a method buildSessionFactory () given by configuration cla
In order to get a session (or) open a session we need to called openSession ( ) given
SessionFactory it means SessionFactory produces a Session (open conn)
While working with insert ,update, delete operation from an hibernate application
on to the dbase. Then hibernate needs a logical transaction.
If we are loading (select command) an object from the dbase we do not required any
ction in hibernate.
gin a logical transaction in hibernate then we need to call a method beginTransaction () givn by Session inte
ansaction tx = Session .beginTransaction ()
Step 6:- use the methods given by session interface for too and from transferring the
data in the form of object Session .save (obj) Session. Delete (obj);
………..etc
Step 7:- if any Exception occurs then hibernate will automatically Rollback (cancel) on the database.
As a programmer after the operation are completed on the dbase .we need to commit
the transaction .
sessionFactory Syntax
Factory.close ()
ATION:-
work s/w is nothing but, working with (or) adding the jar file provided by that java application.
not an installable s/w.
ramework s/w , w will get a zip file and we need to on zip it, to get the jar file required.
ollow some common principal
will be in the form of a set of jar files, where one jar file acts as main jar file and remaining jar file, will acts a
2) each framework s/w application contains at least one configuration file but
multip[le configuration files are also allowed.
In order to setup the Fw environment into a java application, the configuration file
is the first one to be loaded into a java application.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
27
JAVA Means DURGASOFT
www.sourceforge.net/projects/hibernat/files/hibernates
1. Antlr-2.7.6.jar
2. Asm.jar
Cglib-2.1.3.jar
Commons-collections-2.1.1.jar
Commons-logging-1.0.4.jar
Domuj-1.6.1.jar 7.
1)the following app is to java an object of product class in database. Hibernat app
Product.java
Product.hbm.xml
Hibernate.cfg.xml
// product.java
product
{
Private int productid; Private string productnam; Private double price;
Public void setproductid (int productid)
Return productid;
This.productname = productname;
Return productname;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
29
JAVA Means DURGASOFT
This.price = price;
Return price;
PRODUCT.HBM.XML:-
<! DOCTYPE------
<! Product.html.xml..>
“/>
</id>
HIBERNATE.CFG.XML :-
..
<!—hibernate.cfg.xml
<hibernate- configuration>
m.xml’/>
s is our original java programe this application is doing to stove the object in db.fot this using hibernate conc
.hibernate.cfg.*; Class clint forsave
//step:
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
32
JAVA Means DURGASOFT
Con.configuration (“ hibernate.cfg.xml’);
//step 3:
// step 5 :
//Step6:
//Step 7:
//step 8
Session .clase ( );
// step 9
Factory. Clase
();
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
33
JAVA Means DURGASOFT
In the example mapping file , for the property price, we have not included
column attribute the reason is, the property name and column name both are one
and same.
In the above mapping file, for <id>element , we used a sub element called generator,
signd it’s meaning is the programmer manually insert to the value for the
operty. Hibernate does not generate any id value
ovide a generate class for the < id> element then hibernate by default assumes the generator class as assi
product id “ =column = “p id”>
Is equal to
In the above client application, we used save () given by session interface. Internally
hibernate generate an insert statement and for all statements, hibernate uses
preparedstatement of jdbc internally
IMPORTANT POINTS:-
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
34
JAVA Means DURGASOFT
If the configuration file name is hibernate.cfg.xml then following two statements are
one and same.
e two methods, it is possibl is select load only one object at a time from the dbase .becaz we are passing an
a product object, whose id is then the following statement is required.
n.load ( product. Class, nw integer of (111));
a java programe, automatically java compiler acts a public static property called class of type class.
When we want a class object then we can all that static class property of the class
BEFORE COMPILING:-
…….
..
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
36
JAVA Means DURGASOFT
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
37
JAVA Means DURGASOFT
Product p = (product) o; Sop ( p. getPrice ()); Session. Close (); Factory. Close ()
}}
NOTE:-in the above client application we have not started any logical transaction of
hibernate becaz loading an object from a db does not belong to any transactional operation.
SessionFactory Factory = new configuration (). Configure (). Build SessionFactory ();
STEP 2:- click on file menu new project select java-project next enter
projects name (example) finish.
Copy doctype
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
39
JAVA Means DURGASOFT
<hibernate- mapping>
</id>
</class>
</hibernate – mapping>
ernate properties.
..
..
..
</ property>
t java buildpath at leftside selectbrowes tab click and externalize button select jar files required op
terclass-name (insert client) finish
//insert client :-
Import org.hibernate.*;
Import org.hibernate.cfg.*;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
41
JAVA Means DURGASOFT
P class insertclient
s.setstudentName (“
Session.sav (s);
Fx.commit ();
}}
STEP 8:- to run the client application , R T click on the client java file run
as java application
42 DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
JAVA Means DURGASOFT
1) Load an object from the database and modify it’s values. Now
hibernate automatically modifies the valus on to dbase also, whenever a
transaction is committed.
43 DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
JAVA Means DURGASOFT
2) If we want modify an object then we can create a new object with same
id and we can all update() given by session interface
APPROACH 1:- whenever an object to is loaded from the dbase then hibernate
stores the loaded object in a coach memory maintained by session.
iii) If we modified the loaded object for multiple times then also the
modifications will be stored in the object maintains by the cache
memory.
iv) Whenever we issue commit operation then hibernate verifies whether any
changes are there b/w the object stored in cache memory and the object
stored in dbase. If changes exist then hibernate automatically updates the
dbase also by generating an update operation.
v) Hibernate automatically maintains b/w the cache memory objects and
dbase tables row
p. setprice(2500);
APPROACH 1:- in this approach we need load object from the bd we will
create new object and we will assigne same id number and we will call update
method explicitly in order to make changes on the object that is stored in the
dbase.
.hibernate. *;
ory factory = new configuration () .configure () build SessionFactory () Session session = Factory.open Sess
ession. Load (product.class, new integer (111))
product)o;
45 DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
Transaction fx= session begin Transaction ();
p. set price
(2500); fx.commit
() session. Clos
() factory. Close
();
}}
In the above app we have the product of price if a time, but hibernate generate
only a single updation operation only and the object stored in dbase.
Deleting an object :-if we want delete an object from the dbase then load that
object from the dbase and call delete() given by session interface.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
46
VERSIONING AN OBJECT:-1) once an object is save in a dbase, we can modify that
object for any no. of times.
2 .If we want to know that how many number of times an object is modifies
then w need to apply this versioning concept.
Private int
studentid; String
studentname ;
Private int v;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
47
STUDENT.HBM.XML
<h-m>
<class.>
<id->
<gen,>
</id>
</p.>
</p->
</h-m>
1) STUDENT . JAVA:-
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
48
Private int v;
Return v;
This. V= V;
STUDENT. HBM.XML
<doc type..
<hibernate – mapping>
</id>
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
49
JAVA Means
DURGASOFT
</class>
Main ()
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
50
sessionFactory factory = new configuration. Configuration
session close ()
factory.close ()
} }
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
51
After modifying the object :-
// update client
}}
If we use time stop the hibernate automatically records stores the current system
date and time information in to the database.
In the pojo class take a property of type timestamp along with th other properties
of the class and generate setter and getter methods for it
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
52
In the hbm.xml file, configure < timestamp> element and it must be configure
immediately of < id>
{ <class ---
-- </p--->
-- </p--->
} </class>
</h—m>
While hibernate creating the table, hibernate uses the data type of timestamp
column as date so in the dbase only date is saved but not time
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
53
If we want record both date and time then we need to explicitly alter the t
stamp column type as timestamp. Otherwise a programmer can explicitly
We are assinge some values of that object . We are saving that object in db.
Student s= new student. s.set student (101); s.setStudent name (“abc”); s.set marks (500);
session. Save (s); session. Close ();
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
54
LIFE CYCL OF A POJO OBJECT IN HIBERNATE:-
2) when an object is in transient state it does not represent any row of the database.
3) when an object is in transient state the it does not have any association
with the session object.
If we modify the data of a pojo class object when it is in transint state then it
does not effect on the dbase table.
Student s = null
(101); S = (student ) o;
Session .close ()
5) before a pojo class object enters into a session then it will be in transient state.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
55
6) if we want to convert a transient object into persistent state then we
have the following two approachs 1) by saving that object.
8) If we want save an object in the data base then we need to call any one
of the following 3 methods. I) save ii) persist() iii) save or update ()
9) If w want to load an object from the database then we need to call eithr
load () or get ()
(101); s= (student ) o;
f. commit ()
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
56
4) If we want move an object from persistent state into detached state, we
need to either close that session or we need clear of that cache memory
of the session or we need to remove that particular object from the coach
memory of the session.
5) If we want move an object from persistent state to transient state then we
need delete from the object from the dbase.
57
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
// states client. Java :- import org.
P class statesclient
Session Factory factory = new configuration (). Configure buildsession factory ();
state
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
58
JAVA Means
DURGASOFT
Session. Close
();
Factory.Close();
} }
q) what is the diff b/w a primitive type and wrapper type in a pojo class of hibernate ?
a) if we use primitive type and if we are not interested to set the value for it then
at the time of saving an object in database the value zero is inserted in that
column.
Because zero is the value , so there is a chance of miss understanding the data
S1.setmarks (850);
59
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, AmeerpetJAVA
, Hyd.Means
Ph: 040-64512786
DURGASOFT
Session session = factory .open session();
2) in this conversion , if that session is already having an object with the same
id then hibernate throws exception because in hibernate , a session can
maintaine only one object with the same.
4) merge () will merge combine two object into one object , if the two objects
are rep the same id.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
60
5) update () and the merge() bothe are used for converting or moving an
object from detachd state into persistent state againe.
S2= (student)o1;
Fx. Commit;
Sessions close
()
61 DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
Instated of calling th update () we need to call marge () in order to convert
s1 from detached state into persistent state.
Session.merge (s1)
In this type of hierarchy, hibernate uses a simple table in the database for storing the
base class data and all it’s derived classes data in the databse.
In this type of hierarchy hibernate needs an addition column in the table called
discriminator column this discriminator column is mandatory, while writing with table
per class hierarchy
In table perclass hierarchy while writing hibernate mapping file, we need to use <
discriminator > element and < subclass > element newly in the xml file
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
62
JAVA Means DURGASOFT
By this inheritance strategy, we can map the whole hierarchy by single table
only. Here, an extra column (also known asdiscriminator column) is
created in the table to identify the class.
Let's understand the problem first. I want to map the whole hierarchy given
below into one table of the database.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
63
JAVA Means DURGASOFT
There are three classes in this hierarchy. Employee is the super class for
Regular_Employee and Contract_Employee classes. Let's see the mapping
file for this hierarchy.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
64
JAVA Means DURGASOFT
In this example we are creating the three classes and provide mapping of these classes in the employee.hbm.xml file.
You need to create the persistent classes representing the inheritance. Let's
create the three classes for the above hierarchy:
File: Employee.java
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
65
JAVA Means DURGASOFT
1. package com.javatpoint.mypackage;
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. //getters and setters
8. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Regular_Employee extends Employee{
4. private float salary;
5. private int bonus;
6.
7. //getters and setters
8. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Contract_Employee extends Employee{
4. private float pay_per_hour;
5. private String contract_duration;
6.
7. //getters and setters
8. }
File: employee.hbm.xml
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
66
JAVA Means
DURGASOFT
6. <hibernate-mapping>
7. <class name="com.javatpoint.mypackage.Employee" table="emp121" discri
minator-value="emp">
8. <id name="id">
9. <generator class="increment"></generator>
10. </id>
11.
12. <discriminator column="type" type="string"></discriminator>
13. <property name="name"></property>
14.
15. <subclass name="com.javatpoint.mypackage.Regular_Employee" discrim
inator-value="reg_emp">
16. <property name="salary"></property>
17. <property name="bonus"></property>
18. </subclass>
19.
20. <subclass name="com.javatpoint.mypackage.Contract_Employee" discri
minator-value="con_emp">
21. <property name="pay_per_hour"></property>
22. <property name="contract_duration"></property>
23. </subclass>
24.
25. </class>
26.
27. </hibernate-mapping>
Open the hibernate.cgf.xml file, and add an entry of mapping resource like
this:
1. <mapping resource="employee.hbm.xml"/>
File: hibernate.cfg.xml
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
67
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
5.
6. <hibernate-configuration>
7.
8. <session-factory>
9. <property name="hbm2ddl.auto">update</property>
10. <property name="dialect">org.hibernate.dialect.Oracle9Dialect<
/property>
11. <property name="connection.url">jdbc:oracle:thin:@localhost:1
521:xe</property>
12. <property name="connection.username">system</property>
13. <property name="connection.password">oracle</property>
14. <property name="connection.driver_class">oracle.jdbc.driver.Or
acleDriver</property>
15. <mapping resource="employee.hbm.xml"/>
16. </session-factory>
17.
18. </hibernate-configuration>
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
68
4) Create the class that stores the persistent object
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
1. package com.javatpoint.mypackage;
2. import org.hibernate.*;
3. import
org.hibernate.cfg.*; 4.
5. public class StoreData {
6. public static void main(String[] args) {
7. Session session=new Configuration().configure("hibernate.cfg.xml")
8. .buildSessionFactory().openSession();
9.
10. Transaction t=session.beginTransaction();
11.
12. Employee e1=new Employee();
13. e1.setName("sonoo");
14.
15. Regular_Employee e2=new Regular_Employee();
16. e2.setName("Vivek Kumar");
17. e2.setSalary(50000);
18. e2.setBonus(5);
19.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
69
20.
21. Contract_Employee e3=new Contract_Employee();
22. e3.setName("Arjun Kumar");
23. e3.setPay_per_hour(1000);
24. e3.setContract_duration("15 hours");
25.
26. session.persist(e1);
27. session.persist(e2);
28. session.persist(e3);
29.
30. t.commit();
31. session.close();
32. System.out.println("success");
33. }
34. }
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
70
Output:
In case of Table Per Subclass, subclass mapped tables are related to parent
class mapped table by primary key and foreign key relationship.
The <joined-subclass> element of class is used to map the child class with
parent using the primary key and foreign key relation.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
71
Let's see how can we map this hierarchy by joined-subclass element:
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
72
9. <class name="com.javatpoint.mypackage.Employee" table="emp123">
10. <id name="id">
11. <generator class="increment"></generator>
12. </id>
13.
14. <property name="name"></property>
15.
16. <joined-
subclass name="com.javatpoint.mypackage.Regular_Employee" table="rege
mp123">
17. <key column="eid"></key>
18. <property name="salary"></property>
19. <property name="bonus"></property>
20. </joined-subclass>
21.
22. <joined-
subclass name="com.javatpoint.mypackage.Contract_Employee" table="con
temp123">
23. <key column="eid"></key>
24. <property name="pay_per_hour"></property>
25. <property name="contract_duration"></property>
26. </joined-subclass>
27.
28. </class>
29. </hibernate-mapping>
In case of table per subclass class, there will be three tables in the
database, each representing a particular class.
The joined-subclass subelement of class, specifies the subclass.
The key subelement of joined-subclass is used to generate the foreign key
in the subclass mapped table. This foreign key will be associated with the
primary key of parent class mapped table.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
73
JAVA Means DURGASOFT
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
74
JAVA Means DURGASOFT
In this example we are creating the three classes and provide mapping of
these classes in the employee.hbm.xml file.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
75
JAVA Means DURGASOFT
You need to create the persistent classes representing the inheritance. Let's
create the three classes for the above hierarchy:
File: Employee.java
1. package com.javatpoint.mypackage; 2.
public class Employee {
private int id;
private String name; 6.
7. //getters and setters 8. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage; 2.
public class Regular_Employee extends Employee{
private float salary;
private int bonus; 6.
7. //getters and setters 8. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Contract_Employee extends Employee{
4. private float pay_per_hour;
5. private String contract_duration;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
76
JAVA Means DURGASOFT
6.
7. //getters and setters
8. }
File: employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3.
4. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
6.
7.
8. <hibernate-mapping>
9. <class name="com.javatpoint.mypackage.Employee" table="emp123">
10. <id name="id">
11. <generator class="increment"></generator>
12. </id>
13.
14. <property name="name"></property>
15.
16. <joined-
subclass name="com.javatpoint.mypackage.Regular_Employee" table="rege
mp123">
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
77
JAVA Means DURGASOFT
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
1. <mapping resource="employee.hbm.xml"/>
File: hibernate.cfg.xml
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
78
JAVA Means DURGASOFT
In this class, we are simply storing the employee objects in the database.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
79
JAVA Means DURGASOFT
File: StoreData.java
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.*;
4. import
org.hibernate.cfg.*; 5.
6. public class StoreData {
7. public static void main(String[] args) {
8. Session session=new Configuration().configure("hibernate.cfg.xml")
9. .buildSessionFactory().openSession();
10.
11. Transaction t=session.beginTransaction();
12.
13. Employee e1=new Employee();
14. e1.setName("sonoo");
15.
16. Regular_Employee e2=new Regular_Employee();
17. e2.setName("Vivek Kumar");
18. e2.setSalary(50000);
19. e2.setBonus(5);
20.
21. Contract_Employee e3=new Contract_Employee();
22. e3.setName("Arjun Kumar");
23. e3.setPay_per_hour(1000);
24. e3.setContract_duration("15 hours");
25.
26. session.persist(e1);
27. session.persist(e2);
28. session.persist(e3);
29.
30. t.commit();
31. session.close();
32. System.out.println("success");
33. }
34. }
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
80
JAVA Means DURGASOFT
In case of Table Per Concrete class, there will be three tables in the
database having no relations to each other. There are two ways to map the
table with table per concrete class strategy.
By union-subclass element
By Self creating the table for each class
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
81
JAVA Means
DURGASOFT
5. <hibernate-mapping>
6. <class name="com.javatpoint.mypackage.Employee" table="emp122">
7. <id name="id">
8. <generator class="increment"></generator>
9. </id>
10.
11. <property name="name"></property>
12.
13. <union-
subclass name="com.javatpoint.mypackage.Regular_Employee" table="rege
mp122">
14. <property name="salary"></property>
15. <property name="bonus"></property>
16. </union-subclass>
17.
18. <union-
subclass name="com.javatpoint.mypackage.Contract_Employee" table="con
temp122">
19. <property name="pay_per_hour"></property>
20. <property name="contract_duration"></property>
21. </union-subclass>
22.
23. </class>
24.
25. </hibernate-mapping>
In case of table per concrete class, there will be three tables in the
database, each representing a particular class.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
82
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
83
The table structure for each table will be as follows:
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
84
JAVA Means
DURGASOFT
In this example we are creating the three classes and provide mapping of
these classes in the employee.hbm.xml file.
You need to create the persistent classes representing the inheritance. Let's
create the three classes for the above hierarchy:
File: Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. //getters and setters
8. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Regular_Employee extends Employee{
4. private float salary;
5. private int bonus;
6.
7. //getters and setters
8. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Contract_Employee extends Employee{
4. private float pay_per_hour;
5. private String contract_duration;
6.
7. //getters and setters
8. }
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
85
The mapping has been discussed above for the hierarchy.
File: employee.hbm.xml
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
1. <mapping resource="employee.hbm.xml"/> Now the configuration file will look like this: File: hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
t">
5.
6. <hibernate-configuration>
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
87
7. <session-factory>
8. <property name="hbm2ddl.auto">update</property>
9. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</prop
erty>
10. <property name="connection.url">jdbc:oracle:thin:@localhost:1
521:xe</property>
11. <property name="connection.username">system</property>
12. <property name="connection.password">oracle</property>
13. <property name="connection.driver_class">oracle.jdbc.driver.Or
acleDriver</property>
14. <mapping resource="employee.hbm.xml"/>
15. </session-factory>
16.
17. </hibernate-configuration>
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.*;
4. import
org.hibernate.cfg.*; 5.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
88
6. public class StoreData {
7. public static void main(String[] args) {
8. Session session=new Configuration().configure("hibernate.cfg.xml")
9. .buildSessionFactory().openSession();
10.
11. Transaction t=session.beginTransaction();
12.
13. Employee e1=new Employee();
14. e1.setName("sonoo");
15.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
89
Table Per Concrete class
In case of Table Per Concrete class, there will be three tables in the
database having no relations to each other. There are two ways to map the
table with table per concrete class strategy.
By union-subclass element
By Self creating the table for each class
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
90
Let's see how can we map this hierarchy by union-subclass element:
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
91
19. <union-
subclass name="com.javatpoint.mypackage.Contract_Employee" table="con
temp122">
20. <property name="pay_per_hour"></property>
21. <property name="contract_duration"></property>
22. </union-subclass>
23.
24. </class>
25.
26. </hibernate-mapping>
In case of table per concrete class, there will be three tables in the
database, each representing a particular class.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
92
JAVA Means DURGASOFT
In this example we are creating the three classes and provide mapping of
these classes in the employee.hbm.xml file.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
93
JAVA Means DURGASOFT
You need to create the persistent classes representing the inheritance. Let's
create the three classes for the above hierarchy:
File: Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. //getters and setters
8. }
File: Regular_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Regular_Employee extends Employee{
4. private float salary;
5. private int bonus;
6.
7. //getters and setters
8. }
File: Contract_Employee.java
1. package com.javatpoint.mypackage;
2.
3. public class Contract_Employee extends Employee{
4. private float pay_per_hour;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
94
JAVA Means DURGASOFT
File: employee.hbm.xml
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
95
JAVA Means DURGASOFT
Open the hibernate.cgf.xml file, and add an entry of mapping resource like
this:
1. <mapping resource="employee.hbm.xml"/>
File: hibernate.cfg.xml
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
96
JAVA Means DURGASOFT
17.
18. </hibernate-configuration>
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
1. package com.javatpoint.mypackage;
2.
3. import org.hibernate.*;
4. import
org.hibernate.cfg.*; 5.
6. public class StoreData {
7. public static void main(String[] args) {
8. Session session=new Configuration().configure("hibernate.cfg.xml")
9. .buildSessionFactory().openSession();
10.
11. Transaction t=session.beginTransaction();
12.
13. Employee e1=new Employee();
14. e1.setName("sonoo");
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
97
JAVA Means DURGASOFT
15.
16. Regular_Employee e2=new Regular_Employee();
17. e2.setName("Vivek Kumar");
18. e2.setSalary(50000);
19. e2.setBonus(5);
Composite primary keys means having more than one primary key, let us
see few points on this concept
If the table has a primary key then in the hibernate mapping file we need
to configure that column by using <id /> element right..!
Even though the database table doesn’t have any primary key, we must
configure one column as id (one primary key is must)
If the database table has more than one column as primary key then we call
it ascomposite primary key, so if the table has multiple primary key columns
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
98
JAVA Means
DURGASOFT
Example On this
Files required….
Product.java (Pojo)
ForOurLogic.java (for our logic)
hibernate.cfg.xml
Product.hbm.xml
Product.java
packagestr;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
99
publicclassProduct implementsjava.io.Serializable{
privatestaticfinallongserialVersionUID=1L;
privateintproductId; privateStringproName;
privatedoubleprice;
publicvoidsetProductId(intproductId)
this.productId=productId;
publicintgetProductId()
returnproductId;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
100
publicvoidsetProName(StringproName)
this.proName=proName;
publicStringgetProName()
returnproName;
publicvoidsetPrice(doubleprice)
this.price=price;
publicdoublegetPrice()
returnprice;
}
}
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
101
JAVA Means DURGASOFT
hibernate.cfg.xml
<?xmlversion='1.0'encoding='UTF-8'?>
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
102
JAVA Means
DURGASOFT
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="Product.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
Product.hbm.xml
<?xmlversion="1.0"?>
<hibernate-mapping>
<class name="str.Product"table="products">
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
103
<composite-id>
</composite-id>
<property name="price"/>
</class>
</hibernate-mapping>
ForOurLogic.java
packagestr;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
104
importorg.hibernate.*;
importorg.hibernate.cfg.*;
publicclassForOurLogic{
publicstaticvoidmain(String[]args)
{
Configuration cfg=newConfiguration(); cfg.configure("hibernate.cfg.xml");
SessionFactory factory=cfg.buildSessionFactory();
Session session=factory.openSession();
Productp=newProduct();
p.setProductId(101);
p.setProName("iPhone");
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
105
p.setPrice(25000);
Transaction tx=session.beginTransaction();
session.save(p);
tx.commit();
session.close();
factory.close();
Notes:
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
106
come to Product.hbm.xml, see line number 9-12, this time we are using one
new element<composite-id>
Actually if we have a single primary key, we need to use <id> element,
but this time we have multiple primary keys, so we need to use this new
element <composite-id>
Actually we will see the exact concept of this composite primary keys in the
next example (loading an object with composite key)
Although you can use SQL statements directly with Hibernate using Native SQL but I
would recommend to use HQL whenever possible to avoid database portability hassles,
and to take advantage of Hibernate's SQL generation and caching strategies.
Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties
like table and column names are case sensitive in HQL.
FROM Clause
You will use FROM clause if you want to load a complete persistent objects into
memory. Following is the simple syntax of using FROM clause:
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
107
String hql ="FROM Employee";
Query query =session.createQuery(hql);
List results =query.list();
If you need to fully qualify a class name in HQL, just specify the package and class
name as follows:
108 DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
JAVA Means DURGASOFT
WHERE Clause
If you want to narrow the specific objects that are re
ORDER BY Clause
To sort your HQL query's results, you will need to use the ORDER BY clause. You can order the resu
GROUP BY Clause
This clause lets Hibernate pull information from the database and group it based on a
value of an attribute and, typically, use the result to include an aggregate value.
Following is the simple syntax of using GROUP BY clause:
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
109
JAVA Means DURGASOFT
UPDATE Clause
Bulk updates are new to HQL with Hibernate 3, and d
3 than they did in Hibernate 2. The Query interface no
110
JAVA Means
DURGASOFT
DELETE Clause
The DELETE clause can be used to delete one or more objects. Following is the simple
syntax of using DELETE clause:
String hql ="DELETE FROM Employee "+ "WHERE id =
Query query =session.createQuery(hql); query.set
System.out.println("Rows affected: "+ result);
INSERT Clause
HQL supports INSERT INTO clause only where records can be inserted f
Criteria API
HCQL (Hibernate Criteria Query Language)
The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the specific criteria. The C
Advantage of HCQL
The HCQL provides methods to add criteria, so it is easy for the java
programmer to add criteria. The java programmer is able to add many
criteria on a query.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
111
Criteria Interface
The Criteria interface provides many methods to specify criteria. The object
of Criteria can be obtained by calling thecreateCriteria() method of Session
interface.
Restrictions class
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
112
1. public static SimpleExpression lt(String propertyName,Object
value) sets the less than constraint to the given property.
2. public static SimpleExpression le(String propertyName,Object
value) sets the less than or equalconstraint to the given property.
3. public static SimpleExpression gt(String
propertyName,Object value) sets the greater than constraint
to the given property.
4. public static SimpleExpression ge(String propertyName,Object
value) sets the greater than or equalthan constraint to the given
property.
Order class
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
113
JAVA Means DURGASOFT
2. List list=c.list();
1. Crietria c=session.createCriteria(Emp.class);
2. c.setFirstResult(10);
3. c.setMaxResult(20);
4. List list=c.list();
Example of HCQL to get the records whose salary is greater than 10000
1. Crietria c=session.createCriteria(Emp.class);
2. c.add(Restrictions.gt("salary",10000));//salary is the propertyname
3. List list=c.list();
Example of HCQL to get the records in ascending order on the basis of salary
1. Crietria c=session.createCriteria(Emp.class);
2. c.addOrder(Order.asc("salary"));
3. List list=c.list();
1. Criteria c=session.createCriteria(Emp.class);
2. c.setProjection(Projections.property("name"));
3. List list=c.list();
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
114
JAVA Means DURGASOFT
Relation Ships
By many-to-one element
By one-to-one element
In this example, one employee can have one address and one address
belongs to one employee only. Here, we are using bidirectional association.
Let's look at the persistent classes.
Employee.java
1. package com.javatpoint;
2.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
115
JAVA Means DURGASOFT
Address.java
1. package com.javatpoint; 2.
public class Address {
private int addressId;
private String addressLine1,city,state,country;
private int pincode;
private Employee employee;
//setters and getters 9. }
employee.hbm.xml
In this mapping file we are using one-to-one element in both the mapping files to make the one to one mapping.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
116
JAVA Means DURGASOFT
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Employee" table="emp212">
8. <id name="employeeId">
9. <generator class="increment"></generator>
10. </id>
11. <property name="name"></property>
12. <property name="email"></property>
13.
14. <one-to-one name="address" cascade="all"></one-to-one>
15. </class>
16.
17. </hibernate-mapping>
address.hbm.xml
This is the simple mapping file for the Address class. But the important thing
is generator class. Here, we are using foreigngenerator class that depends
on the Employee class primary key.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
117
JAVA Means DURGASOFT
3) Configuration file
This file contains information about the database and mapping file.
hibernate.cfg.xml
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
118
JAVA Means DURGASOFT
8.
9. <session-factory>
10. <property name="hbm2ddl.auto">update</property>
11. <property name="dialect">org.hibernate.dialect.Oracle9Dialect<
/property>
12. <property name="connection.url">jdbc:oracle:thin:@localhost:1
521:xe</property>
13. <property name="connection.username">system</property>
14. <property name="connection.password">oracle</property>
15. <property name="connection.driver_class">oracle.jdbc.driver.Or
acleDriver</property>
16. <mapping resource="employee.hbm.xml"/>
17. <mapping resource="address.hbm.xml"/>
18. </session-factory>
19.
20. </hibernate-configuration>
Store.java
1. package com.javatpoint;
2. import org.hibernate.cfg.*;
3. import org.hibernate.*;
4.
5. public class Store {
6. public static void main(String[] args) {
7. Configuration cfg=new Configuration();
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
119
JAVA Means DURGASOFT
8. cfg.configure("hibernate.cfg.xml");
9. SessionFactory sf=cfg.buildSessionFactory();
10. Session session=sf.openSession();
11. Transaction tx=session.beginTransaction();
12.
13. Employee e1=new Employee();
14. e1.setName("Ravi Malik");
15. e1.setEmail("[email protected]");
16. Address address1=new Address();
17. address1.setAddressLine1("G-21,Lohia nagar");
18. address1.setCity("Ghaziabad");
19. address1.setState("UP");
20. address1.setCountry("India");
21. address1.setPincode(201301);
22.
23.
24. e1.setAddress(address1);
25. address1.setEmployee(e1);
26.
27. session.persist(e1);
28. tx.commit();
29.
30. session.close();
31. System.out.println("success");
32. }
33. }
Fetch.java
1. package com.javatpoint;
2. import java.util.Iterator;
3. import java.util.List;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
120
JAVA Means DURGASOFT
4. import org.hibernate.Query;
5. import org.hibernate.Session;
6. import org.hibernate.SessionFactory;
7. import
org.hibernate.cfg.Configuration; 8.
9. public class Fetch {
10. public static void main(String[] args) {
11. Configuration cfg=new Configuration();
12. cfg.configure("hibernate.cfg.xml");
13. SessionFactory sf=cfg.buildSessionFactory();
14. Session session=sf.openSession();
15.
16. Query query=session.createQuery("from Employee e");
17. List<Employee> list=query.list();
18.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
121
JAVA Means DURGASOFT
If the persistent class has list object that contains the entity reference, we
need to use one-to-many association to map the list element.
Here, we are using the scenario of Forum where one question has multiple
answers.
In such case, there can be many answers for a question and each answer
may have its own informations that is why we have used list in the
persistent class (containing the reference of Answer class) to represent a
collection of answers.
Let's see the persistent class that has list objects (containing Answer class
objects).
1. package com.javatpoint;
2.
3. import java.util.List;
4.
5. public class Question {
6. private int id;
7. private String qname;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
122
JAVA Means DURGASOFT
The Answer class has its own informations such as id, answername,
postedBy etc.
1. package com.javatpoint;
2.
3. public class Answer {
4. private int id;
5. private String answername;
6. private String postedBy;
7. //getters and setters
8.
9. }
10. }
The Question class has list object that have entity reference (i.e. Answer
class object). In such case, we need to use one-to-many of list to map this
object. Let's see how we can map it.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
123
JAVA Means DURGASOFT
In this example, we are going to see full example of mapping list that
contains entity reference.
Question.java
1. package com.javatpoint; 2.
3. import java.util.List; 4.
public class Question {
private int id;
private String qname;
private List<Answer> answers; 9.
Answer.java
1. package com.javatpoint;
2.
3. public class Answer {
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
124
JAVA Means DURGASOFT
Here, we have created the question.hbm.xml file for defining the list.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
125
JAVA Means DURGASOFT
This file contains information about the database and mapping file.
8.
9. <session-factory>
10. <property name="hbm2ddl.auto">update</property>
11. <property name="dialect">org.hibernate.dialect.Oracle9Dialect<
/property>
12. <property name="connection.url">jdbc:oracle:thin:@localhost:1
521:xe</property>
13. <property name="connection.username">system</property>
14. <property name="connection.password">oracle</property>
15. <property name="connection.driver_class">oracle.jdbc.driver.Or
acleDriver</property>
16. <mapping resource="question.hbm.xml"/>
17. </session-factory>
18.
19. </hibernate-configuration>
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
126
JAVA Means DURGASOFT
1. package com.javatpoint;
2. import java.util.ArrayList;
3. import org.hibernate.*;
4. import
org.hibernate.cfg.*; 5.
6. public class StoreData {
7. public static void main(String[] args) {
8. Session session=new Configuration().configure("hibernate.cfg.xml")
9. .buildSessionFactory().openSession();
10. Transaction t=session.beginTransaction();
11.
12. Answer ans1=new Answer();
13. ans1.setAnswername("java is a programming language");
14. ans1.setPostedBy("Ravi Malik");
15.
16. Answer ans2=new Answer();
17. ans2.setAnswername("java is a platform");
18. ans2.setPostedBy("Sudhir Kumar");
30.
31. ArrayList<Answer> list2=new ArrayList<Answer>();
32. list2.add(ans3);
33. list2.add(ans4);
34.
35. Question question1=new Question();
36. question1.setQname("What is Java?");
37. question1.setAnswers(list1);
38.
39. Question question2=new Question();
40. question2.setQname("What is Servlet?");
41. question2.setAnswers(list2);
42.
43. session.persist(question1);
44. session.persist(question2);
45.
46. t.commit();
47. session.close();
48. System.out.println("success");
49. }
50. }
OUTPUT
Here, we have used HQL to fetch all the records of Question class including
answers. In such case, it fetches the data from two tables that are functional
dependent. Here, we are direct printing the object of answer class, but we
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
128
JAVA Means DURGASOFT
FetchData.java
1. package com.javatpoint;
2. import java.util.*;
3. import org.hibernate.*;
4. import
org.hibernate.cfg.*; 5.
6. public class FetchData {
7. public static void main(String[] args) {
8.
9. Session session=new Configuration().configure("hibernate.cfg.xml")
10. .buildSessionFactory().openSession();
11.
12. Query query=session.createQuery("from Question");
13. List<Question> list=query.list();
14.
15. Iterator<Question> itr=list.iterator();
16. while(itr.hasNext()){
17. Question q=itr.next();
18. System.out.println("Question Name: "+q.getQname());
19.
20. //printing answers
21. List<Answer> list2=q.getAnswers();
22. Iterator<Answer> itr2=list2.iterator();
23. while(itr2.hasNext()){
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
129
JAVA Means DURGASOFT
24. System.out.println(itr2.next());
25. }
26.
27. }
28. session.close();
29. System.out.println("success");
30. }
31. }
We can map many to many relation either using set, bag, map etc. Here,
we are going to use map for many-to-many mapping. In such case, three
tables will be created.
Question.java
User.java
question.hbm.xml
user.hbm.xml
hibernate.cfg.xml
StoreTest.java
FetchTest.java
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
130
JAVA Means DURGASOFT
Question.java
1. package com.javatpoint;
2.
3. import java.util.Map;
4.
5. public class Question {
6. private int id;
7. private String name;
8. private Map<String,User> answers;
9.
10. public Question() {}
11. public Question(String name, Map<String, User> answers) {
12. super();
13. this.name = name;
14. this.answers = answers;
15. }
16. public int getId() {
17. return id;
18. }
19.
20. public void setId(int id) {
21. this.id = id;
22. }
23. public String getName() {
24. return name;
25. }
26. public void setName(String name) {
27. this.name = name;
28. }
29. public Map<String, User> getAnswers() {
30. return answers;
31. }
32. public void setAnswers(Map<String, User> answers) {
33. this.answers = answers;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
131
JAVA Means DURGASOFT
34. }
35.
36.
37. }
User.java
1. package com.javatpoint;
2.
3. public class User {
4. private int id;
5. private String
username,email,country; 6.
7. public User() {}
8. public User(String username, String email, String country) {
9. super();
10. this.username = username;
11. this.email = email;
12. this.country = country;
13. }
14. public int getId() {
15. return id;
16. }
17.
18. public void setId(int id) {
19. this.id = id;
20. }
21.
22.
23. public String getUsername() {
24. return username;
25. }
26.
27. public void setUsername(String username) {
28. this.username = username;
29. }
30.
31. public String getEmail() {
32. return email;
33. }
34.
35. public void setEmail(String email) {
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
132
JAVA Means DURGASOFT
question.hbm.xml
user.hbm.xml
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.User" table="user738">
8. <id name="id">
9. <generator class="native"></generator>
10. </id>
11. <property name="username"></property>
12. <property name="email"></property>
13. <property name="country"></property>
14. </class>
15.
16. </hibernate-mapping>
hibernate.cfg.xml
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
134
JAVA Means DURGASOFT
StoreTest.java
1. package com.javatpoint;
2.
3. import java.util.HashMap;
4. import org.hibernate.*;
5. import org.hibernate.cfg.*;
6. public class StoreTest {
7. public static void main(String[] args) {
8. Session session=new Configuration().configure().buildSessionFactory().open
Session();
9. Transaction tx=session.beginTransaction();
10.
11. HashMap<String,User> map1=new HashMap<String,User>();
12. map1.put("java is a programming language",
13. new User("John Milton","[email protected]","usa"));
14.
15. map1.put("java is a platform",
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
135
JAVA Means DURGASOFT
FetchTest.java
1. package com.javatpoint;
2. import java.util.*;
3. import org.hibernate.*;
4. import org.hibernate.cfg.*;
5. public class FetchTest {
6. public static void main(String[] args) {
7. Session session=new Configuration().configure().buildSessionFactory().ope
nSession();
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
136
JAVA Means DURGASOFT
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786
137