0% found this document useful (0 votes)
2 views

Hibernate (1)

Hibernate is a framework that provides various features for object-relational mapping (ORM), including support for relational databases, full-text search, validation, and NoSQL datastores. It was developed by Gavin King and has evolved since its inception in 2001, with significant releases improving its capabilities and compliance with Java standards. Key features include automatic table creation, caching support, and a simplified data access layer, making it a popular choice for enterprise applications following the MVC architecture.

Uploaded by

gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Hibernate (1)

Hibernate is a framework that provides various features for object-relational mapping (ORM), including support for relational databases, full-text search, validation, and NoSQL datastores. It was developed by Gavin King and has evolved since its inception in 2001, with significant releases improving its capabilities and compliance with Java standards. Key features include automatic table creation, caching support, and a simplified data access layer, making it a popular choice for enterprise applications following the MVC architecture.

Uploaded by

gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Hibernate

Hibernate is having many futures like

Hibernate ORM
Domain model persistence for relational databases

Hibernate Search
Full-text search for your domain mode

Hibernate Validator
Annotation based constraints for your domain model

Hibernate OGM
Domain model persistence for NoSQL datastores

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.
 In early 2003, the Hibernate development team began Hibernate2 releases,
which offered many significant improvements over the first release.
 JBoss, Inc. (now part of Red Hat) later hired the lead Hibernate developers in
order to further its development.

 In 2005, Hibernate version 3.0 was released. Key features included a new
Interceptor/Callback architecture, user defined filters, and JDK
5.0 Annotations (Java's metadatafeature). As of 2010, Hibernate 3 (version
3.5.0 and up) was a certified implementation of the Java Persistence API
2.0 specification via a wrapper for the Core module which provides
conformity with the JSR 317 standard.[3]
 In Dec 2011, Hibernate Core 4.0.0 Final was released. This includes new
features such as multi-tenancy support, introduction of ServiceRegistry (a
major change in how Hibernate builds and manages "services"), better Session
opening from SessionFactory, improved integration
via org.hibernate.integrator.spi.Integrator and auto
discovery,internationalization support and message codes in logging, and a
clearer split between API, SPI and implementation classes.[4]
 In Dec 2012, Hibernate ORM 4.1.9 Final was released.[5]
 In Apr 2014 , Hibernate ORM 4.3.5 Final was released.[5]

Hibernate ORM
Where we can contribute as a hibernate developer?
While making MVC based architecture Applications
We can contribute under Data Access Layer (DAO)
Before Hibernate what we have to make DAO’s?

For making DAO classes in industry they used to depends on EJB entity
beans+jdbc

Features of EJBEntity beans ?

i. Portable Object Relations for making Persistence layer


ii. Caching support (bean managed ,container managed)
iii. QL(query language)database independent language support
iv. Hide Implementations and we can access through Interface
references(data abstraction)

EJBEntity beans disadvantages ?

i. Dependency of application server


ii. Less productive (take more time for implementation)
iii. Compile time Exception Handling while using jdbc code
iv. Complete Invasive Strictly force us to impalement EJb classes

Futures of Hibernate ?

i. It will provide Portable Object Relationship(associations , Inheritance)


ii. Caching support(session level ,Session Factory level)
iii. HQL support, hibernate Query Language (database independent queries
developer can write ,at runtime it will fire queries on underlying
Database )
iv. Criteria support (we can pass conditional query’s in very easy manner )
v. Named parameters support (run time values we can pass to query’s)
vi. No need of compile time Exception handling here they refitted to run time
exceptions
vii. Auto DDL support (table creation , updating and deletion)
viii. Auto primary key incrimination
ix. No Application Server dependency

Usually for making enterprise applications software industry will fallows MVC rules.
As per MVC Application should divide into 3sub layers

Presentation BusinessData Access

For making Abstraction On each layer they will put Interfaces on top of their
Implementations

Presentation Business Interface  Data Access Interface

Business Implementations Data Access implementation

So we know as a hibernate developer we should make Data Access layer


Then The common requirements in Data Access layer is

i. Create tables in database(database dba will provide these tables)


ii. save records into database(ex: student details want to store in database)
iii. update records into database(ex: student details want to update in
database)
iv. delete records from database(ex: student details want to delete from
database)
v. select records with condition(ex: student details want to select from
database by applying condition like where sroll=1220)
vi. select some records (ex: select students details only male or select student
who is having marks between 500 to 550)
vii. select All (ex: All students details want to see)
viii. store data into temp files for the caching and to reduce database calls

So if I use Hibernate Can I achieve all these ?


Yes we can provide all these futures by using hibernate

Application architecture by using MVC

Model Objects

N_______
i.Read data from form
E_______ i. Business operations
ii.send to Model layer
Dao operations using
A_______ ii.cal Data Access Layer for
DB operations hibernate
Presentation
Business Layer DAO
Layer
Controller(servle
t)
Hibernate Architecture

Model Objects

Model Object to Table Mapping Configuration file


File(hbm.xml)

Database Connection Properties


Configuration Manager

Hibernate Factory Configurations

Second level Cache files


Session Factory(no of sessions will maintainer)

session session session

Auto schema generation

DATA ACCES OBJECT

Save(){
DB1 DB2 DB3
}update(){
Ex:Oracle Ex:MySql EX:IBM DB2
}delete(){ …
}Select(){

Model Object:
a. It will store data(state) in Objects state before moving object into database
state .
b. It will store data into objects state while selecting data from database

This model objects can have 3 states

i. Transient state:
After object creation if we not attach that object to any session
Then we can say that object in Transient state.
ii. Persistent states:

Transient object if it attached with hibernate session then we can say


that object is in Persistent state .This state will store data permanently in
data storage (RDBMS, NoSql DBMS)

iii. Detached State:


If we close session or evict the object from the session then that evicted
object we can call Detached Object
i. How to use ?
Use any IDE to make hibernate application or else you can do in legacy
manner (through command prompt by putting all required hibernate
dependencies in to class path)

Sample1:

i. Download hibernate jars


http://sourceforge.net/projects/hibernate/files/hibernate4/4.3.5.Final/
hibernate-release-4.3.5.Final.zip/download
extract from zip to folder
ii. open folder find lib->required10 jar files (required dependencies)

Open Eclipse Create work space click on OK

Create new java project name it


StudentReg
Add jar files from the extracted folder required jar files

Add required jar files from hibernate downloads and add


database dependent jar file
#Open Student.java write sample

#Open StudentDaointerface.java write sample

#Open StudentDaoImpl write sample


package com.company.app.repository;
import …
public class StudentDaoImpl implements StudentDaoInterface {
@Override
public int save(Student student) throws Exception{
Session session=HibernateSessionFactory.
getSessionFactory().openSession();
Transaction transaction=session.beginTransaction();
int id=(Integer)session.save(student);
transaction.commit();
session.close();
return id;
}
}
#Open HibernateSessionFactory.java write sample(Singleton
Factory class)

#Open hibernate.properties file write sample


These are database connection properties (note we can configure
these properties in hibernate.cfg.xml file also)
#Open hibernate.cfg.xml file write sample

#Open student.hbm.xml write sample


#Open StudentController.java write sample

Run It
It will create table in your specified database and stores data
Auto DDL support(hbm2ddl.auto)
Hibernate tool will provide us auto ddl support .this support will
provide us
i. auto table creation in database along with
relationships(create table)
ii. auto table update in database(alter table)
iii. validating table with the existing table
structure
iv. auto table creation and drop options
are we can achieve here by default
under hibernate configurations we have one property
hibernate.hbm2ddl.auto=”create”
(or)
hibernate.hbm2ddl.auto=”update”
(or)
hibernate.hbm2ddl.auto=”validate”
(or)
hibernate.hbm2ddl.auto=”create-drop”
by configuring this property in hibernate.properties file or
hibernate.cfg.xml file we can achive this auto ddl
sample for hbm2ddl.auto
#Create java project Name:AutoDdlTest add hibernate jars

#Open HibernateSessionFactory write sample


#Open Test.java write sample

#Open Student.java write sample (copy from previous example)


#Open hibernate.properties (copy from previous example)
#Open hibernate.cfg.xml file(copy from previous properties)
Make changes in hibernate.cfg.xml file while Running Test
class
i. RUN Test class when:
<property name="hbm2ddl.auto">create</property>
ii. RUN Test class when:
<property name="hbm2ddl.auto">update</property>

iii. RUN Test class when:


<property name="hbm2ddl.auto">validate</property>

iv. RUN Test class when:


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

Open Database and check table structure in each test


Primary key& Composite primary key
Primary key: unique identity for each record
Composite primary key: combination of 2 or more
columns data should be Unique for each record
As per database normalizations each table should have
one primary key column to make select operation easy
So here hibernate will fallow at least first normal form so
with out primary key field we can able to create a table
First Normal Form (1NF):

A row of data cannot contain repeating group of data i.e each


column must have a unique value. Each row of data must have a
unique identifier i.e Primary key.
Ex:

SID SNAME EMAIl


1220 Naveen [email protected]
1221 Naveen1 [email protected]
1222 Naveen [email protected]
In this table SID is the primary key field
You can configure any column name of your model object in
hibernate mapping file id attribute to make it as a primary key
Field
Ex:

In student.hbm.xml file in case of Id as a primary key


To make a non integer Email as a primary key
Mapping file Tags and Attributes
public class Student {
private int id;
private String name;
private String email;
private String address;
private Date jdate;

//generate getters and setters

<!DOCTYPE hibernate-mapping PUBLIC


"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.Student" table="student007" schema="system">
<id name="id" column="sid" length="10" type="integer"/>

<property name="name" column="sname" type="string"


length="30" not-null="true" unique="true"/>

<property name="email" column="semail" type="string"


length="30" not-null="true" unique="true"/>

<property name="address" column="saddress" type="string"


length="30" not-null="true" unique="true"/>

<property name="jdate" column="sjdate" type="date"


not-null="true"/>
</class>

</hibernate-mapping>
id tag:
i. id tag property for primary key filed mapping we have to
use
ii. by default id property filed is not null field
and we can use id property field we can use for foreign
key
Attributes:
name=”bean property fieldname”
column=”table column name”
length=”10” (required size we can specify here)
type=”datatype for database”
***allowed datatypes:

attributes:
Auto Primary key
(<id><generator class=”assigned”/> </id>)
Hibernate providing us one more great feature auto primary key
incrimination)
So that the primary key field values we no need to pass at run
time automatically hibernate will increment id is based on
generator we configured under hibernate.properties or
hibernate.cfg.xml file
We have Different primary key generators
i. Assigned
ii. Increment
iii. Identity
iv. Sequence
v. Hilo
vi. Native(identity, sequence, hilo)
vii. Foreign

Where to configure this property

i. assigned:
in case of assigned generator user must pass id value hibernate
will not provide any value (default generator is assigned)

#Open student.hbm.xml file write sample


#Open Test class and write sample
Run and open database view records

ii. increment:
in case of increment hibernate will do select max id operation first
and it will add +1 to the existing id and insert the object values into
database with out taking id value from the user
This generator supports in all the databases, database independent

# Run Test class and view records in table


iii. Identity:
In case of identity database should takecare about the
primary key increment hibernate will not do any max(id)
select Operator here like incerement generator
And it is database dependent(oracle will not support)
#Open student.hbm.xml file

Hibernate.properties
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost:3306/root
hibernate.connection.username = root
hibernate.connection.password = root
iv. Sequence:
In case of sequence hibernate will create one default
sequence in database
hibernate-sequence and get nextval from the sequence for
the next insertion
and initial value is 1and it will cerement by +1 in default
hibernate-sequence

#Open student.hbm.xml file write sample

Run Test class view record in database


If you want provide custom sequence. create one sequence in database
and set that sequence name under <generator> child tag <param>
Custom Sequence

CREATE SEQUENCE student_seq


START WITH 1000
INCREMENT BY 2
NOCACHE
NOCYCLE;
#Open student.hbm.xml file write sample

Run Test class view records


v. Hilo:
i. This generator is database independent
for the first record, the id value will be inserted as 1
for the second record the id value will be inserted as 32768
for the next records the id value will be incremented by
32768 and will stores into the database (i mean adds to the
previous)
#Open student.hbm.xml file write sample

Run Test view records


Caching Support
In a three tier architecture, the application tier and data tier can be
in different hosts. Throughput of the application is affected by the
network speed. This network overhead will be avoided by having the
database at the application tier. As commercial databases are heavy
weight, it is not practically feasible to have the application and the
database at the same host. There are lot of light-weight databases
available on the market, which can be used to cache data from the
commercial databases.
Caching will provide us support of data from application layer
instead of getting data from database by hitting sql queries it will give us
from caches what was we prepared under application layer.

DATA LAYER
APPLICATION

LAYER

Cache
provider

Cached data
Hibernate have 2 types of caching supports
i. First level Cache (build in cache)(session level)
ii. Second Level cache(pluggable cache)(SessionFactory level)

i. First Level Cache:


With out adding any external plug-in we can achieve first level
cache
How it will work?
If we select any record from database by using session references
that retrieved data it will keep in the from of objects that objects
references it will keep along with it until calling evict() method of
Session or calling close() method
ex:
Example:

Open Eclipse create java project


Add hibernate jar files

Open student .java write sample


Open student.hbm.xml write sample

Open hibernate.Properties configure properties


hibernate.connection.driver_class =
oracle.jdbc.OracleDriver
hibernate.connection.url =
jdbc:oracle:thin:@localhost:1521:xe
hibernate.connection.username = system
hibernate.connection.password = manager

Open hibernate.cfg.xml file write sample


<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">validate</property>
<property name="show_sql">true</property>
<property name="format_sql">false</property>
<mapping resource="./student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Show_sql will show us hibernate generated sqlquerys

Write a client

public class Client {


public static void main(String[] args) {

Configuration cfg=new Configuration();


cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();

Student st=(Student)s.get(Student.class,new Integer(1));

System.out.println(st.getName());
System.out.println(st.getEmail());
System.out.println(st.getAdderss());

//s.evict(st);

Student st1=(Student)s.get(Student.class,new Integer(1));

System.out.println(st1.getName());
System.out.println(st1.getEmail());
System.out.println(st1.getAdderss());

}
}

Test without evict method and with evict method find the difference
ii. Second Level Cache(Session Factory):
Second level cache will store data under file system up to some
time after that it will flush data from file . this hibernate second
level cache will work if we add cache provider jar file and
required configurations .

Cache providers: Description

EHCache It can cache in memory or on disk and


clustered caching and it supports the optional
Hibernate query result cache.
OSCache Supports caching to memory and disk in a
single JVM, with a rich set of expiration policies
and query cache support.
swarmCache A cluster cache based on JGroups. It uses
clustered invalidation but doesn't support the
Hibernate query cache
JBoss Cache A fully transactional replicated clustered cache
also based on the JGroups multicast library. It
supports replication or invalidation,
synchronous or asynchronous communication,
and optimistic and pessimistic locking. The
Hibernate query cache is supported
Every cache provider is not compatible with every concurrency strategy.
The following compatibility matrix will help you choose an appropriate

Sno Cache Read- Nonstrictread- Read- Transactional


provider only write write
1 EHCache Yes Yes Yes No
2 OScache Yes Yes Yes No
3 swarmCache Yes Yes No No
4 JBoss Cache Yes Yes No No
1.x,2.x

Lets see one example by using EHCache


Along with hibernate.properties and configuration file configure one
ehcache.xml file in any of your applications
ehcache.xml

<ehcache>
<diskStore path="user.dir" />
<defaultCache maxElementsInMemory="50"
timeToIdleSeconds="1000" timeToLiveSeconds="1000"
overflowToDisk="true" eternal="false"/>
</ehcache>
diskStore path="user.dir":
 user.home - User's home directory
 user.dir - User's current working directory
 java.io.tmpdir - Default temp file path
 ehcache.disk.store.dir - A system property you would normally specify
on the command line—for example, java
-Dehcache.disk.store.dir=/u01/myapp/diskdir

timeToIdleSeconds:
The maximum number of seconds an element can exist in the cache
without being accessed. The element expires at this limit and will no
longer be returned from the cache. The default value is 0, which means no
timeToIdle (TTI) eviction takes place (infinite lifetime).
timeToLiveSeconds:
The maximum number of seconds an element can exist in the cache
regardless of use. The element expires at this limit and will no longer be
returned from the cache. The default value is 0, which means no
timeToLive (TTL) eviction takes place (infinite lifetime).
eternal="false":
If it is true it will over ride TTIS and TTLS values those two options it will
disable in case of true So that no expiration can takes place
And Concurrency strategy can apply in hbm file
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="Employee" schema="system">
<cache usage="read-write"/>
<id name="eid" column="EID">
<generator class="hilo"></generator>
</id>
<property name="ename" column="ENAME"/>
<property name="email" column="EEMAIL"/>
<property name="esal" column="ESAL"/>
</class>
</hibernate-mapping>

And have to add these properties in hibernate.cfg.xml file to activate second level
cache
<property name="cache.use_second_level_cache">true</property>
<!-- cache provoder EhCache-->
<property name="cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property>
Hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools. -->


<hibernate-configuration>

<session-factory>
<!—database configurations-->
<!—hibernate defaults-->
<!-- caching config -->
<property name="cache.use_second_level_cache">true</property>
<!-- cache provoder EhCache-->
<property name="cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property>
<mapping resource="Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
Model Objects Relations
Model objects can be have association and inheritance relations as per
our object oriented analysis
i. A Model object can have parent child relation
ii. A Model object can have any other class object as a parameter
iii. A Model object can have any Collection Object as a parameter

When and Why?


When I should use this object relation ships and why
While working on ORM tool there is no need of table relation ships
externally if we provide that relations ships among the objects that
objects are capable to manage relations between tables so as a Object
oriented programmer no need to focus relations on table level externally

Inheritance Relations:

While inheriting a class from another class how to store parent and child
bean information into table
Lets check for example
If have parent bean and child bean how to store properties
There are 3 ways to store these properties
i. Table per class
ii. Table per sub class
iii. Table per Concrete class
Table per class:
In case of table per class parent bean and child bean information
will store under one table only
How to create Mapping File
How to create Beans

Class ParentBean{
private datatype p1;
private datatype p2;
private datatype p3;
//getter and setters
}
Class ChildBean1 extends ParentBean{
private datatype c1;
private datatype c2;
private datatype c3;
//getter and setters
}
Class ChildBean2 extends ParentBean{
private datatype c11;
private datatype c12;
private datatype c13;
//getter and setters
}
Class ChildBean3 extends ParentBean{
private datatype c21;
private datatype c22;
private datatype c23;
//getter and setters
}
II. Table per sub class:

If client don’t want to use the single table for multiple beans (null entries
are inserting for other bean properties column). So that if you want to
create a separate table for each bean go through Table per sub class.

While inserting data If you give id for parent bean the same id it will
insert into child bean properties table .If you use any auto primary key
incrimination techniques here those will work if hbm2ddl create by
default hibernate will use +1 increment .So while applying auto primary
key try to configure hbm2ddl validate
How to create Mapping File
How to create beans
Class ParentBean{
private datatype p1;
private datatype p2;
private datatype p3;
//getter and setters
}
Class ChildBean1 extends ParentBean{
private datatype c1;
private datatype c2;
private datatype c3;
//getter and setters
}
Class ChildBean2 extends ParentBean{
private datatype c11;
private datatype c12;
private datatype c13;
//getter and setters
}
Class ChildBean3 extends ParentBean{
private datatype c21;
private datatype c22;
private datatype c23;
//getter and setters
}
III . Table per concrete class:
If you want store data from onto separate tables with out any parent
table references directly child bean data along with parent bean data if
you want to store in a separate table .then go through table per concrete
class relation ship.

If you use assign generator then same if we can insert in multiple table
but incase of auto primary key it will apply auto increment operation by
joining all tables
How to create mapping file?
How to create beans
Class ParentBean{
private datatype p1;
private datatype p2;
private datatype p3;
//getter and setters
}
Class ChildBean1 extends ParentBean{
private datatype c1;
private datatype c2;
private datatype c3;
//getter and setters
}
Class ChildBean2 extends ParentBean{
private datatype c11;
private datatype c12;
private datatype c13;
//getter and setters
}
Class ChildBean3 extends ParentBean{
private datatype c21;
private datatype c22;
private datatype c23;
//getter and setters
}

Apply the above scenarios in deferent ways to realize it


Employee bean sub employee beans and
Car bean and sub car beans kind of scenarios try to implement
Associations:
Association is a king of relation ship between objects one object can
contain another objects properties in it with out extending
Like If student has a property Course in it
Like If Mother has a property Child in it

We can describe associations in four ways those are

i. One-to-one relation ship


ii. One-to-Many relation ship
iii. Many-to-one relation ship
iv. Many-to-Many relation ship

i. One to One relation:


Here one object should contain only one object that means one
table record should have relation with only one record in
associated table
Like: One Voter should have only one Polled Vote in polling table

Ex:

public class Voter {


private int vid;
private String vname;
private String vdetails;
//generate getters and setters
}
public class VotesPoll {
private int vpid;
private String pname;
private String date;
private Voter voter;
//generate getters and setters
}

Voter.hbm.xml file

VotesPoll.hbm.xml file
First Insert Voter details later votespoll values insert by giving voter id as a
reference that id will store as a primary key field in VotesPoll table
So the same key it will try to insert as a primary key filed in votesPoll .

ii. One – to-Many :


Here one object can contain any number of objects in the form of
List or Set that means one table record can contain relation ship
with no of records in another table by using primary key foreign
key relation ship
package com.govt.adhar.model;
public class Mother {
private int id;
private String name;
private String email;
private String bgroup;
private Set<Child> child;
//generate getters and setters
}

package com.govt.adhar.model;
public class Child {
private int id;
private String name;
private String email;
private String bgroup;
//generate getters and setters
}
Mother.hbm.xml file
Child.hbm.xml file

So in Above example we are assigning primary key of Mother as a foreign


key ref in Child table. So while inserting each child record the
corresponding parent reference also will insert as a foreign key .
i. Many-to-one relation ship

You might also like