Hibernate Short Note
Hibernate Short Note
Hibernate is the ORM tool given to transfer the data between a java (object) application
and a database (Relational) in the form of the objects.
Hibernate is the open source, light weight tool given by Gavin King, actually JBoss server
is also created by this person only.
Hibernate is a non-invasive framework, means it won’t forces the programmers to
extend/implement any class/interface, and
Hibernate we have all POJO classes so its light weight.
Hibernate can runs with in or without server, i mean it will suitable for all types of java
applications (stand alone or desktop or any servlets bla bla.)
Hibernate is purely for persistence (to store/retrieve data from Database).
Mapping and Configuration are very familiar keywords we used to hear in the hibernate,
every hibernate program must need these 2 xml files.
Mapping File:
The mapping file contains mapping from a pojo class name to a table name and pojo
class variable names to table column names.
While writing an hibernate application, we can construct one or more mapping files,
mean a hibernate application can contain any number of mapping files.
Identity (Object Name)
State (Object values)
Behavior (Object Methods)
But while storing an object into the database, we need to store only the values(State) right ?
but how to avoid identity, behavior.. its not possible. In order to inform what value of an object
has to be stored in what column of the table, will be taking care by the mapping, actually
mapping can be done using 2 ways,
XML
Annotations.
<hibernate-mapping>
</hibernate-mapping>
Configuration:
Configuration is the file loaded into an hibernate application when working with hibernate,
this configuration file contains 3 types of information..
Connection Properties
Hibernate Properties
Mapping file name(s)
xml
By writing Properties file. We don’t have annotations hear, actually in hibernate 1, 2.x
we defined this configuration file by writing .properties file, but from 3.x xml came into picture.
so, finally
Mapping –> xml, annotations
Configuration –> xml, .properties (old style)
Syntax Of Configuration xml:
<hibernate-configuration>
<session-factory>
<propertyname="connection.user">user </property>
<propertyname="connection.password">password</property>
<property name="show_sql">true/false</property>
</session-factory>
</hibernate-configuration>
Hibernate supports Inheritance, Associations, Collections
In hibernate if we save the derived class object, then its base class object will also be
stored into the database, it means hibernate supporting inheritance
Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-
Many, Many-To-One
This will also supports collections like List,Set,Map (Only new collections)
In jdbc all exceptions are checked exceptions, so we must write code in try, catch and
throws, but in hibernate we only have Un-checked exceptions, so no need to write try, catch, or
no need to write throws. Actually in hibernate we have the translator which converts checked
to Un-checked
Hibernate has capability to generate primary keys automatically while we are storing
the records into database
Hibernate has its own query language, i.e hibernate query language which is database
independent
So if we change the database, then also our application will works as HQL is database
independent
HQL contains database independent commands
While we are inserting any record, if we don’t have any particular table in the database,
JDBC will rises an error like “View not exist”, and throws exception, but in case of hibernate, if it
not found any table in the database this will create the table for us
Hibernate supports caching mechanism by this, the number of round trips between an
application and the database will be reduced, by using this caching technique an application
performance will be increased automatically.
Hibernate supports annotations, apart from XML
Hibernate provided Dialect classes, so we no need to write sql queries in hibernate,
instead we use the methods provided by that API.
Getting pagination in hibernate is quite simple.
Disadvantages of hibernates:
Any hibernate application, for example consider even first hello world program must always
contains 4 files totally.
POJO class
Mapping XML
Configuration XML
One java file to write our logic
Private intstNo;
{
this.stNo=stNo;
}
{
Return stNo;
}
{
this.stName=stName;
}
{
Return stName;
}
{
this.stAddress=stAddress;
}
Public int getStAddress()
{
Return stAddress;
}
}
Mapping xml For POJO:
Hear is the mapping file related to above pojo class, if you have any doubts on the syntax of the
Mapping xml file, you can check our previous session
<hibernate-mapping>
<class name="Java4s"table="STable">
<generator class="assigned"/>
</id>
</hibernate-mapping>
Yes., see in this above mapping xml, for stAddress property i have not written any column name
i just been specified <property name=”stAddress “/>, this means in the database the column
name for stAddress property will also be stAddress, in these cases we can ignore the column
attribute to write, and i will explain about this <generator /> element later.
Configuration XML
<?xmlversion='1.0'encoding='UTF-8'?>
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory“>
<propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<propertyname="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<propertyname="connection.user">user</property>
<propertyname="connection.password">password</property>
<propertyname="show_sql">true</property>
<propertyname="dialet">org.hibernate.dialect.OracleDialect</property>
<propertyname="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
Let us see what are the jar files we need to download to work with hibernate framework, and
how to install.
Working with the framework software is nothing but, adding the .jar(s) files provided by that
framework to our java application. Each framework software is not an installable software, it
means we do not contain any setup.exe
When we download any framework software, we will get a ‘zip‘ file and we need to unzip it, to
get the jar files required, actually all framework softwares will follow same common principles
like…
Framework software will be in the form of a set of jar files, where one jar file acts as
main (We can call this file as core) and remaining will acts as dependent jar files.
Each Framework software contain at least one configuration xml file, but multiple
configuration files also allowed.
In this case, in order to setup the Hibernate framework environment into a java
application, the configuration file is the first one to be loaded into a java application, will see
about this in later sessions.
Hello mates, this is the exact flow of any hibernate application. so you must put little more
concentration while you are reading this post, to understand better.
Whether the java application will run in the server or without server, and the application may
be desktop or stand alone, swing, awt, servlet…what ever, but the steps are common to all.
In order to work with hibernate we don’t required any server as mandatory but we need
hibernate software (.jar(s) files).
Follow The Steps:
1. Import the hibernate API, they are many more, but these 2 are more than enough…
import org.hibernate.*;
import org.hibernate.cfg.*;
2. Among Configuration, Mapping xml files, first we need to load configuration xml, because
once we load the configuration file, automatically mapping file will be loaded as we registered
this mapping xml in the configuration file.
So to load configuration xml, we need to create object of Configuration class, which is given in
org.hibernate.cfg.*; and we need to call configuration() method in that class, by passing xml
configuration file name as parameter.
Eg:
Configuration cf = new Configuration ();
cf.configure(“hibernate.cfg.xml”);
Hear our configuration file name is your choice, but by default am have been
given hibernate.cfg.xml, so once this configuration file is loaded in our java app, then we can
say that hibernate environment is started in our program.
So once we write the line_ cf.configure(“hibernate.cfg.xml”), configuration object cf will reads
this xml file hibernate.cfg.xml, actually internally cf will uses DOM parsers to read the file.
Finally…
Session session = sf.openSession();
sf = SessfionFactory object
4. Create a logical transaction
While working with insert, update, delete, operations from an hibernate application onto the
database then hibernate needs a logical Transaction, if we are selecting an object from the
database then we do not require any logical transaction in hibernate. In order to begin a
logical transaction in hibernate then we need to call a method beginTransaction() given
by Session Interface.
Transaction tx = session.beginTransaction();
session is the object of Session Interface
5. Use the methods given by Session Interface, to move the objects from application to
database and from database to application
session .save(s) - Inserting object ‘s’ into database
SessionFactory object will be created once and will be used by multiple users for long
time.
Session Factory object is the factory for session objects.
If you are using two databases called mysql and oracle in your hibernate application then you
need to build 2 SessionFactory object
Configuration cfg=new Configuration();
Configuration cfg1=cfg.configure(“mysql.cfg.xml”);
SessionFactory sf1=cfg1.builed SessionFactory();
Configuration cfg2=cfg.configure(“oracle.cfg.xml”);
SessionFactory sf2=cfg2.builed SessionFactory();
When we are using more than one database in our application than we use
the HibernateUtil class which is implemented based on singleton design pattern which insure
that one and only one session Factory object will be created for entire application
<?xmlversion="1.0"?>
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="str.Product"table="products">
<version name="v"column="ver"/>
<propertyname="proName"column="pname"length="10"/>
<propertyname="price"/>
</class>
</hibernate-mapping>
Note:
When ever an object of a pojo class is created then it will be in the Transient state
When the object is in a Transient state it doesn’t represent any row of the database, i
mean not associated with any Session object, if we speak more we can say no relation with the
database its just an normal object
If we modify the data of a pojo class object, when it is in transient state then it doesn’t
effect on the database table
When the object is in persistent state, then it represent one row of the database, if the
object is in persistent state then it is associated with the unique Session
if we want to move an object from persistent to detached state, we need to do either
closing that session or need to clear the cache of the session
if we want to move an object from persistent state into transient state then we need to
delete that object permanently from the database
Example____ ClientProgram.java
importorg.hibernate.*;
importorg.hibernate.cfg.*;
public class ClientProgram {
public static void main(String[] args)
{
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
// Transient state_____start
Product p=newProduct();
p.setProductId(101);
p.setProName("iPhone");
p.setPrice(25000);
// Transient state_____end
// Persistent state_____start
Transaction tx = session.beginTransaction();
session.save(p);
System.out.println("Object saved successfully.....!!");
tx.commit();
// Persistent state_____end
session.close();
factory.close();
}
}
Note:
see the above client program, line numbers 16 to 19 we just loaded the object and called the
corresponding setter methods, its not related to the database row
o if you see, line number 24 we called save method in the Session Interface, means the
object is now having the relation with the database
o if we want to convert the object from Transient state to Persistentstate we can do in 2
ways
save()
persist()
saveOrUpdate()
If we want to load an object from database, then we need to call either load() or get() methods
Transient:
One newly created object, without having any relation with the database, means never
persistent, not associated with any Session object
Persistent:
Having the relation with the database, associated with a unique Session object
Detached:
previously having relation with the database [persistent ], now not associated with any Session
see the next sessions for the better understanding of the life cycle states of pojo class object(s)
the hibernate
Inheritance Mapping In Hibernate – Introduction
Compared to JDBC we have one main advantage in hibernate, which is hibernate inheritance.
Suppose if we have base and derived classes, now if we save derived(sub) class object, base
class object will also be stored into the database.
But the thing is we must specify in what table we need to save which object data ( i will explain
about this point later, just remember as of now).
Note: We can also called this Hibernate Inheritance Mapping as Hibernate Hierarchy
Will see these 3 Inheritance Mappings in depth___, friends ensure you are clear about all
previous concepts so far we covered, if not so you may not understand further, please refer
once if you have any doubts.
Hear is the explanation and one example on hibernate table per class hierarchy, consider we
have base class named Payment and 2 derived classes like CreditCard, Cheque
If we save the derived class object like CreditCard or Cheque then automatically Payment class
object will also be saved into the database, and in the database all the data will be stored into
a single table only, which is base class table for sure.
But hear we must use one extra discriminator column in the database, just to identify
which derived class object we have been saved in the table along with the base class object, if
we are not using this column hibernate will throws the exception, see this example so that you
will get one idea on this concept.
Mapping Files:-
<?xmlversion="1.0"?>
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="str.Payment" table="PAYMENT">
<idname="paymentId"column="pid"/>
<subclass name="str.CreditCard"discriminator-value="CC">
<propertyname="CreditCardType"column="cctype"length="10"/>
</subclass>
<subclassname="str.Cheque"discriminator-value="cq">
<propertyname="ChequeType"column="cqtype"length="10"/>
</subclass>
</class>
</hibernate-mapping>
This is also just like previous example, but some changes are there, in table per class
hierarchy all the data was saved in a single table but hear,
x number of classes = x number of tables in the database
If we save the CreditCard class object, then first hibernate will saves the data related
to super class object into the super class related table in the database and then CreditCard
object data in CreditCard related table in the database, so first base class data will be saved
Required files_
All are same but mapping file is different than previous example..
Payment.hbm.xml:
<?xmlversion="1.0"?>
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="str.Payment"table="PAYMENT">
<idname="paymentId"column="pid"/>
<propertyname="amount"column="amt"/>
<joined-subclassname="str.CreditCard"table="CreditCard">
<keycolumn="dummy1"/>
<propertyname="CreditCardType"column="cctype"length="10"/>
</joined-subclass>
<joined-subclassname="str.Cheque"table="Cheque">
<keycolumn="dummy2"/>
<propertyname="ChequeType"column="cqtype"length="10"/>
</joined-subclass>
</class>
</hibernate-mapping>
Something like previous example but the changes are at mapping file only, and one more thing
is..
x number of derived classes = x number of tables in the database
Once we save the derived class object, then derived class data and base class data will
be saved in the derived class related table in the database
for this type we need the tables for derived classes, but not for the base class
in the mapping file we need to use one new element <union-subclass — >under <class
—>
Required files_
Payment.hbm.xml:
<?xmlversion="1.0"?>
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="str.Payment"table="PAYMENT">
<idname="paymentId"column="pid"/>
<propertyname="amount"column="amt"/>
<union-subclassname="str.CreditCard">
<propertyname="CreditCardType"column="cctype"length="10"/>
</union-subclass>
<union-subclassname="str.Cheque">
<propertyname="ChequeType"column="cqtype"length="10"/>
</union-subclass>
</class>
</hibernate-mapping>
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
as composite primary key, so if the table has multiple primary key columns , in order to
configure these primary key columns in the hibernate mapping file we need to use one new
element called <composite-id …..> </composite-id>
Product.hbm.xml
<?xmlversion="1.0"?>
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="str.Product"table="products">
<composite-id>
<key-propertyname="proName"column="pname"length="10"/>
</composite-id>
<propertyname="price"/>
</class>
</hibernate-mapping>
Notes:
see Product.java pojo class, in line number 3 i have implemented
the java.io.Serializableinterface, this is the first time am writing this implementation for the
pojo class right…! we will see the reason why we use this serializable interface later.
But remember, if we want to use the composite primary keys we must implement our
pojo class with Serializable interface
hibernate.cfg.xml is normal as previous programs, something like hello world program
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)
Generators <generator> In Hibernate
Hibernate » | Updated On Apr 07, 2012
<generator /> is one of main element we are using in the hibernate framework [in the mapping
file], let us see the concept behind this generators.
org.hibernate.id.IdentifierGeneratar Interface
The following are the list of main generators we are using in the hibernate framework
assigned
increment
sequence
identify
hilo
native
foregin
uuid.hex
uuid.string
In the above generators list, the first 7 are used for int,long,short types of primary keys, and
last 2 are used when the primary key column type is String type (varchar2)
1 <idname="prodId"column="pid">
2 <generator/>
3 </id>
Increment
1 <id name="productId"column="pid">
2 <generator>
3 <paramname="sequence">MySequence</param>
4 </genetator>
5 </id>
If the programmer has not passed any sequence name, then hibernate creates its own
sequence with name “Hibernate-Sequence” and gets next value from that sequence, and than
assigns that id value for new record
But remember, if hibernate want’s to create its own sequence, in hibernate
configuration file,hbm2ddl.auto property must be set enabled
identity
1 <id name="productid"column="pid">
2 <generator class="......."/>
3 </id>
As this is not working in Oracle, if you would like to check this in MySql you must change the
configuration file as…….
class: com.mysql.jdbc.Driver
url: jdbc:mysql://www.java4s.com:3306/test (test is default database)
user: root (default)
pass: (default)
dialet: org.hibernate.dialet.MySQLDialet
Note:
So far we done the operations on single object (single row), hear we will see modifications,
updates onmultiple rows of data (multiple objects) at a time. In hibernate we can perform the
operations on a single row (or) multiple rows at a time, if we do operations on multiple rows at
once, then we can call this as bulk operations.
HQL is database independent, means if we write any program using HQL commands
then our program will be able to execute in all the databases with out doing any further
changes to it
HQL supports object oriented features
like Inheritance, polymorphism, Associations(Relation ships)
HQL is initially given for selecting object from database and in hibernate 3.x we can
do DMLoperations ( insert, update…) too
Different Ways Of Construction HQL Select
If we want to select a Complete Object from the database, we use POJO class reference
in place of * while constructing the query
In this case (select a complete object from the database) we can directly start our HQL
command from, from key word
Example:
1 // InSQL
4
5 // InHQL
7 [ or]
8 fromProduct p
If we want to load the Partial Object from the database that is only selective properties
(selected columns) of an objects then we need to replace column names with POJO class
variable names.
Example:
1 // InSQL
2
sql> selectpid,pname fromProduct
3
Note: pid, pname are the columns Product isthe tablenameright..!
4
5
// InHQL
6
hql> selectp.productid,p.productName fromProduct p
7
[ or]
8
fromProduct p ( we should notstart from, fromkeyword hear because
9
we selecting the columns hope you are getting me )
10
11
Note: hear p isthe reference...!!
12
productid,productName are POJO variables
Syntax:
1 Query qry = session.createQuery("--- HQL command ---");
2 List l = qry.list();
3 Iterator it = l.iterator();
4 while(it.hasNext())
5 {
6 Object o = it.next();
7 Product p = (Product)o;
9 }
Notes:
<?xmlversion="1.0"?>
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="str.Product"table="products">
<idname="productId"column="pid" />
<propertyname="proName"column="pname"length="10"/>
<propertyname="price"/>
</class>
</hibernate-mapping>
ForOurLogic.java
packagestr;
publicclassForOurLogic {
publicstaticvoidmain(String[] args)
{
cfg.configure("hibernate.cfg.xml");
/*
while(it.hasNext())
{
System.out.println("----------------------");
}
*/
/*
while(it.hasNext())
{
System.out.println("----------------");
}
*/
List l =qry.list();
Iterator it = l.iterator();
while(it.hasNext())
{
Integer i = (Integer)it.next();
System.out.println("Product id : "+i.intValue());
System.out.println("---------------------------");
}
session.close();
factory.close();
}
Unlike HQL, Criteria is only for selecting the data from the database, that to we can select
complete objects only not partial objects, in fact by combining criteria and projections concept
we can select partial objects too we will see this angle later, but for now see how we are
using criteria for selecting complete objects form the database. We cant perform non-
select operations using this criteria. Criteria is suitable for executing dynamic queries too, let us
see how to use this criteria queries in the hibernate..
syntax:
Criteria crit = session.createCriteria(–Our class object–);
Usage:
1 Criteria crit = session.createCriteria(Employee.class);
Adding Conditions To Criteria
If we want to put conditions to load data from database, using criteria then we need to
create one Criterion Interface object and we need to add this object to Criteria Class object
Usage:
Criteria crit = session.createCriteria(Products.class);
1
Criterion c1=Restrictions.gt("price", newInteger(12000));
2
//price is our pojo class variable
3
Note: See line number 2, am calling gt(-,-) method of Restrictions class, (means greater than), in
our above example am fetching the data by comparing price greater than (>) 12000
If we want to put more conditions on the data (multiple conditions) then we can
use and method ,or method give by the Restrictions class
Usage:
1 crit.add(Restrictions.and(Restrictions.like("proName","%R%"),
2 Restrictions.eq("price",newInteger(12000))));
3 List l=crit.list();
4 Iterator it = l.iterator();
packagestr;
importjava.util.Iterator;
importjava.util.List;
importorg.hibernate.Criteria;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.hibernate.cfg.Configuration;
importorg.hibernate.criterion.Criterion;
importorg.hibernate.criterion.Restrictions;
publicclassForOurLogic {
@SuppressWarnings("unchecked")
publicstaticvoidmain(String[] args)
{
cfg.configure("hibernate.cfg.xml");
Criterion cn = Restrictions.gt("price",newDouble(17000));
crit.add(cn);
List l=crit.list();
Iterator it=l.iterator();
while(it.hasNext())
{
Product p=(Product)it.next();
System.out.println(p.getProductId());
System.out.println(p.getProName());
System.out.println(p.getPrice());
System.out.println("-----------------");
}
session.close();
factory.close();
}
Note:
Actually the internal concept is, once we called the list() method in criteria (line number 28) all
objects (records) will come and stores in list object, from there we used to take iterate then
typecast into our POJO class type bla bla.
Hibernate Criteria, Adding Conditions To Criteria
Hibernate » | Updated On Apr 07, 2012
If we want to add some sorting order for the objects, before the objects are going to store in list
object then we need to add an Order class object to the Criteria class object by
calling addOrder() method..,
Native SQL is another technique of performing bulk operations on the data using hibernate
We can use the database specific keywords (commands), to get the data from the
database
While migrating a JDBC program into hibernate, the task becomes very simple because
JDBC uses direct SQL commands and hibernate also supports the same commands by using this
Native SQL
The main draw back of Native SQL is, some times it makes the hibernate application as
database dependent one
If we want to execute Native SQL Queries on the database then, we need to construct an object
of SQLQuery, actually this SQLQuery is an interface extended from Query and it is given in
” org.hibernate package ”
In order to get an object of SQLQuery, we need to use a method createSQLQuery() given by
session interface.
While executing native sql queries on the database, we use directly tables, column
names directly in our command.
Remember, while executing Native SQL Queries, even though we are selecting complete
objects from teh database we need to type cast into object array only, not into our pojo class
type, because we are giving direct table, column names in the Native SQL Querie so it does’nt
know our class name
If we execute the command, always first it will put’s data in ResultSet and from there List
Usage:
1 SQLQuery qry = session.createSQLQuery("select * from PRODUCTS");
3 List l = qry.list();
4 Iterator it = l.iterator();
5 while(it.hasNext())
6 {
7 Object row[] = (Object[])it.next();
8 --- -------
9 }
while selecting data from the table, even though you are selecting the complete object
from the table, in while loop still we type cast into object array only right
See the above code, we typecast into the object[] arrays right.., in case if we want
to type cast into our POJO class (i mean to get POJO class obj), then we need to go
with entityQueryconcept
In order to inform the hibernate that convert each row of ResultSet into an object of the
POJO class back, we need to make the query as an entityQuery
to make the query as an entityQuery, we need to call addEntity() method
Usage:
1 //We are letting hibernate to know our pojo class too
8 --- -------
9 }
Notes:
See line number 2, i have been added addEntity(Product.class) at the end, which will let
the hibernate to know about our POJO class, so now we can typecast into our POJO class type
like what i have done at line number 7
And that’s it, this is the total concept on this Native SQL, am not going to give any
example on this separately hope you understood the concept
Let us see few points, before going to see an example on Named Queries in HIbernate..
1 <hibernate-mapping>
2
3 <classname="---"table="---">
4 <idname="---"column="---" />
5 <propertyname="---"column="---"length="10"/>
6 <propertyname="---"column="---"/>
7 --- --- --- ---
8 </class>
9
12 </query>
13
14 </hibernate-mapping>
Notes:
See line numbers 10,11,12, this is the new element we have to add to work with Named
Queries
there colon (:) java4s is the label, i will pass the value into that label in the run time.., or
let us see the client program logic too
2 qry.setParameter("java4s",newInteger(1022));
3 List l = qry.list();
Notes:
Line number 1, getting the query from hibernate mapping file to our client program
Line number 2, passing run time value to that query
Line number 3, calling list() method to execute the query
Up to now this is the case if we use HQL query in hibernate mapping file, let us see the case if
we would like to use nativeSQL query
Syntax Of hibernate mapping file [For Native SQL]
1 <hibernate-mapping>
2
3 <classname="---"table="---">
4 <idname="---"column="---" />
5 <propertyname="---"column="---"length="10"/>
6 <propertyname="---"column="---"/>
8 </class>
9
12 </sql-query>
13
14 </hibernate-mapping>
Notes:
If we want to give HQL query in hiberante mapping file, we need to use <query/>
element, but we have to use <sql-query /> element in case of Native SQL
See line number 11, its the normal sql command, and PRODUCTS is the table name, not
the pojo class name
Done…!!!!!
Hibernate In Servlet Example, Hibernate In Servlet Tutorial
Hibernate » | Updated On Apr 07, 2012
With servlet, if we want to do some operations on the database, then we can also
use hibernate ORMrather than JDBC. We call this as servlet-Hibernate integration.
While integration servelt with hibernate, it is there to follow these setps
when response for request is too large [If we have 1000's of records in the database]
then instead of displaying all records at a time on browser we can display the
response page by page manner using pagination mechanism
In pagination, initially one page response will be displayed and we will get links for
getting thenext pages response
In this servelt & hibernate integration, we are going to display 4 records or 4 objects of
products using hibernate for selecting the data and we will get links to display the records of
the next pages
Regarding Logic In Order To Get pagination
The servlet accepts pageIndex parameter and if the parameter is passed then servlet
takes the given number as pageIndex, otherwise the servlet will takes the pageIndex as one [ 1
]
Servlet uses Criteria API and the pagination methods of Criteria for loading the records
(objects) related to that particular page, and servlet display those records on the browser
In servlet we use Criteria with projection for finding the total number of records
available in the table, and we store that number into the variable
We will find out the number of hyperlinks required by dividing the total number of
records with records per page
we need to use a loop in order to display the links on the browser, while creating each
link, we use the <a href /> to servlet url pattern [Hiper reference] and by passing that page
nomber as value for pageIndex parameter
One-To-One
Many-To-One
Many-To-Many
One-To-Many
Hibernate One to Many Mapping Insert Query Example
Hibernate » | Updated On Apr 07, 2012
One-to-Many: according to database terminology, one row of table related with multiple rows
of other table
[or]
According to hibernate, one object of one pojo class related to multiple objects of other pojo
I mean, one [parent] to many [Children], example of one-to-many is some thing category books
contains different type of books, one vendor contains lot of customers bla bla.
To achieve one-to-many between two pojo classes in the hibernate, then the following two
changes are required
In the parent pojo class, we need to take a collection property, the collection can be
eitherSet,List,Map (We will see the example on separate collection later)
In the mapping file of that parent pojo class, we need to configure the collection
Let us see the logic for hibernate one to many mapping select query,
hibernate one to many select means, if you select the parent object then automatically its
corresponding child objects will also be selected, see i have given for the logic for selecting
single parent object with all its childs & all parent objects with all child objects
But mates, ensure you came through these sessions for better understand
In the many to one relationship, the relationship is applied from child object to parent
object, but in one to may parent object to child object right..! just remember
many to one is similar to one to many but with the little changes
If we want to apply many to one relationship between two pojo class objects then the
following changes are required
In the child pojo class, create an additional property of type parent for storing the parent object
in child object [ If you are confused just remember you will be able to understand in the
example ], in the child pojo class mapping file we need to write <many-to-one name=”"> for
parent type property unlike <property name=”">
proxy
early loading
In many to one relationship, the lazy attribute (in mapping xml) values are either proxy or false.
If we write lazy=”false” then when ever child object is loading then immediately parent object
will also be loading from the database.
The default value of lazy is proxy, means hear when ever child object is loaded then parent
object is not loaded immediately, but a proxy object will be loaded with it (logical object)
When ever the parent object is accessed then at that moment that parent object will be loaded
from the database.
Note: In our program am not using lazy attribute in xml files so just go ahead and insert this lazy
attribute and test the output on the eclipse console
Hibernate Many to One Mapping Delete Query Example
Hibernate » | Updated On Apr 07, 2012
If we delete child, parent will not deleted because, it may have lot of other child objects
In many to one relationship, when ever a child object is deleted then its parent object is
also deleted, provided if that parent object has no other child objects, means if parent has only
one child, in this case if we delete child, parent will also got deleted, but in all other cases it
willthrows exception
Notes:
See line number 59,60 actually we can save any object either parent or child [ as it is Bi
directional inverse will take automatically ], but in our application i saved child object.
In this above logic, even though we are saving a single child object, but in the
database all child objects are inserted at the time of executing the code, the reason being… the
time of saving c1 object, first its parent object v will be inserted, as the parent object v has 3
child objects so hibernate will save all the 3 child objects in the database
In Vendor.hbm.xml, we have included an attribute in the set element called inverse, this
attribute informs the hibernate that the relation ship is Bi Directional
If we write inverse = “false” then hibernate understands that relationship as
unidirectional and generates additional update operations on the database, so in order to
reduce the internal operations, we need to include inverse=”true“
remember, default value of inverse =”false”
If we make inverse =”true” the performance will be increased, i guess
Let us see an example on this many to many relationship in hibernate. Actually hear there is no
question of unidirectional, only Bi-Directional.
Applying many to many relationship between two pojo class objects is nothing but applying one
to manyrelationship on both sides, which tends to Bi-Directional i mean many to many.
Example:
Let us see this, if we apply many to many association between two pojo class
objects student andcourse, provided the relationship is one student may joined in multiple
courses and one course contains lot of students (joined by multiple students)
Remember, when ever we are applying many to many relationship between two pojo class
objects, on both sides we need a collection property [As we are applying one to many from
both the sides]
Note Points:
While applying many to many relationship between pojo classes, a mediator table is
mandatoryin the database, to store primary key as foreign key both sides, we call this table as
Join table
In many to many relationship join table contain foreign keys only
Main concept of hibernate relations is to getting the relation between parent and child class
objects
Cascade attribute is mandatory, when ever we apply relationship between objects, cascade
attribute transfers operations done on one object onto its related child objects
If we write cascade = “all” then changes at parent class object will be effected to child class
object too, if we write cascade = “all” then all operations like insert, delete, update at parent
object will be effected to child object also
Example: if we apply insert(or update or delete) operation on parent class object, then child
class objects will also be stored into the database.
default value of cascade =”none” means no operations will be transfers to the child class
Example: if we apply insert(or update or delete) operation on parent class object, then child
class objects will not be effected, if cascade = “none”
Cascade having the values…….
In hibernate relations, if we load one parent object from the database then child objects related
to that parent object will be loaded into one collection right (see one-to-many insert example).
Now if we delete one child object from that collection, then the relationship between the
parent object and that child object will be removed, but the record (object) in the database will
remains at it is, so if we load the same parent object again then this deleted child will not be
loaded [ but it will be available on the database ]
so finally what am saying is all-delete-orphan means, breaking relation between objects not
deleting the objects from the database, hope you got what am saying
Note:
what is orphan record ..?
an orphan record means it is a record in child table but it doesn’t have association with its
parent in the application.
[ And ]
In an application, if a child record is removed from the collection and if we want to remove that
child record immediately from the database, then we need to set the cascade =”all-delete-
orphan”
And that’s it about this cascade attribute in hibernate, hope i explained all the values..!!
Joins In Hibernate
Hibernate » | Updated On Apr 07, 2012
Let us see few points regarding this hibernate joins…., like why and where we need to us bla bla
We use join statements, to select the data from multiple tables of the database, when
there existrelationship
with joins, its possible to select data from multiple tables of the database by
construction a singlequery
Left join means, the objects from both sides of the join are selected and more objects
from leftside are selected, even though no equal objects are there at right side
Right join means equal objects are selected from database and more objects are
from right side of join are selected even though there is no equal objects are exist left side
Full join means, both equal and un-equal objects from both sides of join are selected
Inner join means only equal objects are selected and the remaining are discarded
At the time of construction the join statements, we need to use the properties created
in pojo class to apply relationship between the objects
To construct a join statement, we use either HQL, or NativeSql
Left join means, the objects from both sides of the join are selected and more objects from left
side are selected, even though no equal objects are there at right side, no confusion you will be
able tounderstand if you go through this example i guess
Let us see an example on hibernate left join, am taking one-to-many to explain this concept
files required….
Let us try to understand the first level cache in hibernate, actually i tried to give almost all the
concept about this first level cache hope you will enjoy this
By default, for each hibernate application, the first level cache is automatically
been enabled
As a programmer, we no need to have any settings to enable the first level cache and
also we cannot disable this first level cache
the first level cache is associated with the session object and scope of the cache is
limited to one session only
When we load an object for the first time from the database then the object will be
loaded from thedatabase and the loaded object will be stored in the cache memory maintained
by that sessionobject
If we load the same object once again, with in the same session, then the object will be
loaded from the local cache memory not from the database
If we load the same object by opening other session then again the object will loads
from the database and the loaded object will be stored in the cache memory maintained by this
new session
Example
3
7
8 --
9 session.close();
10
11 Session ses2 = factory.openSession();
Explanation:
The loaded objects will be stored in cache memory maintained by a session object and if we
want toremove the objects that are stored in the cache memory, then we need to call
either evict() or clear()methods. Actually evice() is used to remove a particular object from the
cache memory and clear() is toremove all objects in the cache memory
1 Session ses = factory.openSession();
3 Student s = (Student)ob
4 System.out.println(s.getStudentId());
5
6 ses.evict(s);
7
Second level cache in the hibernate is of from 4 vendors…
How to enable second level cache in hibernate
We need one provider class, hear we are going to see hibernate provider class that is EHCache
Changes required
To enable second level cache in the hibernate, then the following 3 changes are required
1 <property name="hibernate.cache.provider_class">
2 org.hibernate.cache.EhCacheProvider
3 </property>
1 <cacheusage="read-only"/>
Important points on this second level cache
If we load student object from the database, then as its the first time hibernate will hits
the database and fetch this student object data and stores in the session1 cache memory [ First
level cache ], then in the global cache [ second level cache ] provided if we write <cache
usage=”read-only” /> in the student mapping file
I mean hibernate will stores in the local session memory by default, but it only stores in
the global cache [ second level cache ] only if we write <cache usage=”read-only” /> in the
student mapping file, if not so hibernate wont stores in the global cache
Now take another session like session 2 for example, if session 2 also load the student
object then hibernate will loads from the global cache [ second level cache ] as student object is
available at global [Actually when ever we want to load any object hibernate first will checks at
local, then global then database right hope you remembered this ], now if session 3 modify that
student object then hibernate will thorows an error because we have written <cache
usage=”read-only” /> in student mapping file
We can avoid this by writing <cache usage=”read-write” />
so remember <cache /> element has that much importance
Mates, still i have not explained about ehcache.xml did you observe i will explain about this
by taking one example on this hibernate second level cache in the next session
Regarding ehcache.xml
Regarding ForOurLogic.java
From line numbers 16 – 22 we opened session1 and loaded object and closed session1,
this time object will be loaded from the database as its the first time
Then from 27 – 31 we have been waited for 6 seconds, but in our ehcache.xml we have
giventimeToIdleSeconds=”5″ , i mean after 5 seconds object will be removed from the global
cache
And again in ForOurLogic.java line numbers 35 – 41 we opened second session and
loaded the object, this time hibernate will loads the object from the database, and closed the
session
Immediately from 43 – 49 we opened session3 and loaded the object, this time
hibernate will loads the object form the global session not from the database
Annotations are introduced in java along with JDK 1.5, annotations are used to
provide META data to the classes, variables, methods of java
Annotations are given by SUN as replacement to the use of xml files in java
In hibernate annotations are given to replace hibernate mapping [ xml ] files
While working with annotations in hibernate, we do not require any mapping files, but
hibernate xml configuration file is must
hibernate borrowed annotations from java persistence API but hibernate it self doesn’t
contain its own annotations
Every annotations is internally an Interface, but the key words starts with @ symbol
Like…..
1 public@interfaceJava4s
2 {
3 // code.....
4 }
For working with annotations, our java version must be 1.5 or higher and hibernate
version must be hibernate 3.3 or higher, actually up to now we have been used hibernate 2.2 in
our previous tutorials, get ready to download the higher version
At j2se level, sun has provided very limited set of annotations like @Override and
@Deprecated …etc…
Sun has provided the annotations related to j2se level
under java.lang.annotations.* package
Most of the annotations related to j2ee level are given by sun and their
implementations are given by the vendors
In hibernate, the annotations supported are given by sun
under javax.persistence package and hibernate has provided implementations for annotations
given in that package
@Entity
@Table
@Id
@Column
Actually @Entity, @Table are class level annotations, and @Id, @Column are the field level
annotations, no worries you will be able to understand while seeing the first example
in hibernate, if we are annotations in the pojo class then hibernate mapping file
is not required, it means annotations are reducing the use of xml files in the hibernate
Though we are using annotations in our pojo class with mapping xml also, then hibernate will
give first preference to xml only not for annotations, actually this concept is same in struts,
hibernate, spring too
And that’s it friends, now you are ready to work with annotations in hibernate
For working with annotations in hibernate, ensure our java version must be 1.5 or higher and
we must use hibernate version 3.3 or higher, and in fact no need to use all the jar files to work
with these annotations.
1 packagestr;
2
3 importjavax.persistence.Column;
4 importjavax.persistence.Entity;
5 importjavax.persistence.Id;
6 importjavax.persistence.Table;
7
8 @Entity
9 @Table(name = "student_talbe")
10 publicclassProduct{
11
12 @Id
13 @Column(name="proid")
14 privateintproductId;
15
16 @Column(name="proName", length=10)
17 privateString proName;
18
19 @Column(name="price")
20 privatedoubleprice;
21
22 publicvoidsetProductId(intproductId)
23 {
24 this.productId = productId;
25 }
26 publicintgetProductId()
27 {
28 returnproductId;
29 }
30
31 publicvoidsetProName(String proName)
32 {
33 this.proName = proName;
34 }
35 publicString getProName()
36 {
37 returnproName;
38 }
39
40 publicvoidsetPrice(doubleprice)
41 {
42 this.price = price;
43 }
44 publicdoublegetPrice()
45 {
46 returnprice;
47 }
48 }
ClientForSave.java
packagestr;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.hibernate.Transaction;
importorg.hibernate.cfg.AnnotationConfiguration;
publicclassClientForSave {
publicstaticvoidmain(String[] args)
{
AnnotationConfiguration cfg=newAnnotationConfiguration();
cfg.configure("hibernate.cfg.xml");
Product p=newProduct();
p.setProductId(105);
p.setProName("java4s");
p.setPrice(15000);
Transaction tx = session.beginTransaction();
session.save(p);
tx.commit();
session.close();
factory.close();
}
}
Vendor.java
1 packagestr;
2
3 importjava.util.Set;
4
5 importjavax.persistence.CascadeType;
6 importjavax.persistence.Column;
7 importjavax.persistence.Entity;
8 importjavax.persistence.FetchType;
9 importjavax.persistence.Id;
10 importjavax.persistence.JoinColumn;
11 importjavax.persistence.OneToMany;
12 importjavax.persistence.Table;
13
14 @Entity
15 @Table(name = "Vendor")
16
17 publicclassVendor{
18
19 @Id
20 @Column(name = "vid")
21 privateintvendorId;
22
24 privateString vendorName;
25
26 publicintgetVendorId() {
27 returnvendorId;
28 }
29
30 publicvoidsetVendorId(intvendorId) {
31 this.vendorId = vendorId;
32 }
33
34 publicString getVendorName() {
35 returnvendorName;
36 }
37
38 publicvoidsetVendorName(String vendorName) {
39 this.vendorName = vendorName;
40 }
41
42 }
1 ------
2 -----
5
6 Student s1 = null;
8 s1 = (Student)o;
9 session1.close();
10
11 s1.setMarks(97);
12
14 Student s2 = null;
16 s2 = (Student)o1;
17 Transaction tx=session2.beginTransaction();
18
19 session2.merge(s1);
Explanation
Hope you are clear…, actually we update and merge methods will come into picture when ever
we loaded the same object again and again into the database, like above.
Folks i have been changed the values in the source code
But hear thing is, save() method can return that primary key id value which is generated by
hibernate and we can see it by
long s = session.save(k);
In this same case, persist() will never give any value back to the client, hope you are clear.