Hibernate (1)
Hibernate (1)
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
Futures of Hibernate ?
Usually for making enterprise applications software industry will fallows MVC 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
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
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
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:
Sample1:
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
</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
i. assigned:
in case of assigned generator user must pass id value hibernate
will not provide any value (default generator is assigned)
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
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
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)
Write a client
System.out.println(st.getName());
System.out.println(st.getEmail());
System.out.println(st.getAdderss());
//s.evict(st);
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 .
<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">
<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
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
}
Ex:
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 .
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