Hibver
Hibver
In the above scenario there are two persistence class called Student & Education. In this one Student will have
multiple Educations. So we need to implement one-to-many relationship between Student & Education.
Cascading: ------------------
Cascading is an automatic task done by the hibernate on persistence objects when persistence objects are in
relationship.
We have two type of cascading: ----------------
Cascading-delete
Cascading-save-update
When you specify the above cascading styles, when one persistent object is deleted hibernate ,delete its
dependence automatically and when one persistence object is saved or updated automatically its dependence
also will be updated.
One attribute is defined called cascade in various tags of hibernate-mapping document to specify the type of
cascading you want to use.
When you are implementing simple java class as persistence ,you need to create the objects and call the
method inside the controller components(when you are following simple MVC model)
Based on the requirement you may migrate the persistence technology or database used in the application.
any migration is happen you need to write new persistence component for that. Then you need to modify
the controller components also which gives you a lot of maintenance.
To solve this problem you need to decouple controller components & persistence component.
So that modification happen on the persistence component does not affect the controller component .
Solution: -------------------- use DAO design patter to decouple the components and to reduce the
maintenance.
Hibernate caching: ------------
.cache is a representation of current database sate near to application.
Cache sits between database and application inside the server where application is running.
NOTE : ----------- implementation the caching technique for read mostly data only. Don’t implement for
write-mostly.
When a transaction is started a new cache will be created. As long as transaction is running cache will be
used with in the transaction. Once the transaction is ended (commit/rollback) cache will be destroyed.
T
Tx cache
Application 1
T
Ses Tx cache
2
T
Tx cache
3
Process cache :------------- this kind of cache will be implemented with the process and for multiple
transaction.
Process level cache will be shared by multiple transactions running within the process.
In this when one transaction is ended hibernate system won’t destroy the cache.
Application T
1
T
Ses 2 Cache
T
3
Clustered scope cache :------------ this kind of cache will be span across multiple processes running in the
multiple remote machines.
Server 1
T
SD 1
Application
Cache
Ses T
2
T Server 2 Database
SD 1
Application Cache
Ses T
2
Clustered Environment
Session Cache
Caching concurrency
Strategies Cache providers
Ses
Stu2
Stu3 Database
ses=sf.openSession();
tx=ses.beginTransaction();
ses.save(stu1); // won’t insert record in database
ses.save(stu2); // won’t insert record in database
student stu3=(Student)ses.load(-,new Integer(99));
stu3.setEmail(“[email protected]”);
// ses.flush();
tx.commit();
stu4=( )ses.load( -, new Integer(99));
ses.delete(stu4);
If you want to delete specified persistent object from the session cache use exict() method.
ses.exict(stu4);
if you want to remove all the persistent object from the session cache use clear() method.
ses.clear();
When you have the collection and association in the class mapping you should provide the cache tag
separately for all. As shown in the following scenario.
Education.java
Student.java
Class Education
Class Student {
{ int edid;
int sid; String course;
String sname; int yop
Set skills; ----- ------------ --------
Set Educations; ----------- ---------------
//set/get methods
----- ------------ -------- }
----------- ---------------
//set/get methods
}
Student.hbm.xml :-------------
4. Call the setCachable(true) method on the query object which contains the servlets of same hibernate
query as follows :----------------------
ses.openSession();
Query q=ses.createQuery(from Student s where s.city=”Bangalore”);
q.setCachable(true);
list list=q.list();
------- ----------
------- ----------
Specify the storage implementation & expiration policies. This implementation varies from cache type to
cache type.
To solve these problems you need to apply the one of the following transactional isolation levels:----------
TRANSACTION-READ-COMMITED 2 No Lock
TRANSACTION-READ-UNCOMMITED 1 Lock column
TRANSACTION-REPEATABLE -READ 4 Lock row
TRANSACTION-SERIALIZABLE 8 Lock Table
To apply the above isolation level you need to write the one of the following four caching concurrency
strategies:---------
Transactional
Read-write
Nonstrict-read-write
Read-only
Transactional
This strategies will be available only in container managed environment.
This strategies maintains the following three isolations level:---------
Committed
Uncommitted
Repeatable-read
Read-write :-----------------
This strategy will be available in container managed environment & non container managed
environment.
This strategies supports the following two isolation levels.
Uncommitted
Committed
It does not support repeatable-read and realizable.
Nonstrict-read-write:---------------------------
Read-only :--------------------
This strategy will be available in both the environments.
It does not maintain any isolation level.
OSCacheProvider
1) It is similar to EhCache.
2) The provider class for this is org.hibernate.cache.OSCacheProvider.
SwarmCacheProvider
Hibernate is design to work with many different environments because of that they provided
large number of configuration parameters.
You can write multiple properties inside hibernate configuration document. Configuration
class, configure method is responsible to read all the properties specified in hibernate
configuration documents and gives you configuration object this configuration object which is
initialized with all the properties will be used to build the SessionFactory object
With the parameters provided by you in the hibernate configuration document session factory
will be created at the beginning of the application.
We can provide the following types of properties in hibernate configuration document.
Hibernate JDBC properties
Hibernate dataSource properties
Hibernate cache properties
Hibernate transaction properties
Other hibernate properties(miscellaneous )
• Generally one application contains one session factory per database. To construct one session factory
you need to provide one configuration document. i.e. for one database you need to write one hibernate
configuration document. For example ------- Oracle.cfg.xml, Mysql.cfg.xml, Cybase.cfg.xml
• When you have multiple databases in your application you need to provide multiple configuration
document so that multiple session factory can be constructed.
Hibernate JDBC properties
When your application is large scale application then C3PO may not suitable for you. For this
scenario use data source which is created and managed by application server.
When you are using hibernate dataSource properties then connection will be obtained from
dataSource object which is register in jndi registry.
List of properties: --------
hibernate.connection.datasource
hibernate.jndi.url (optional)
hinernate.jndi.class (optional)
hibernate.connection.username
hibernate.connection.password
Example: -----
The following example shows how to use dataSource managed by web-logic application server
<hibernate-configuration>
<session-factory>
<property name=”hibernate.connection.datasource”>jdbc/sriMySqlPool</property>
<property name=”hibernate.jndi.url”>t3://localhost:7001</property>
<property name=”hibernate.jndi.class”>web-logic.jndi.WLInitialContextFactory</property>
</session-factory>
</hibernate-configuration>
ctx
Jdbc/mysql pool
Jdbc connections obtained from jndi dataSource will automatically participated in container managed
transaction of the application server.
When you are using dataSource connection then you should use the following two hibernate transaction
properties: -------------
hibernate.transaction.factory-class
hibernate.transaction.manager-lookup-class
Hibernate.connection.properties
list of properties
Hibernate.cache.provider-class
Hibernate.cache.use-query-cache
Hibernate.cache.use-minimal-puts
Hibernate.cache.use-second-level-cache
Hibernate.cache.query_cache_factory
Hibernate.cache. region_prefix
• Use-second-level-cache --------enable/disables
The second level cache
Possible values are true/false.
Default value is true.
This enables all the classes which is specifies cache tag in mapping document.
Use this property to completely disable the second level cache.
• Query-cache-factory:----------- it is used to specify the custom class name for query cache interface.
By default hibernate uses “standard querycache” class.
Region-prefix is a simple name which will be used as prefix to second level cache region.
Hibernate.transaction.property
List of properties
Hibernate.transaction.factory-class
Jta.usertransaction
Hibernate.transaction.manager-lookup-class
Hibernate.transaction.flush-before-completion
Hibernate.transaction.auto-class-session
Factory-class :-------- it is used to specify the custom class of TransactionFactory. The default factory
class is JDBCTransactionFactory.
Jta.userTransaction is used to provide the JNDI name used by JTA TransactionFactory to obtain the
userTransaction object from application server.
Jta.userTransaction is used to provide the JNDI name used by JTATransactionFactory to obtain the
userTransaction object from application server.
Figure
Manager-lookup-class used to provide the custom class name of transactionalmanagerlookup.based
on the application server vendors these subclasses will be changed for example :----------JBOSS
transaction managerLookup,weblogic transactionmanagerlookup.
Flush-before-completion :--------possible rules are true or false. If it is true then session will be
automatically flushed during or before completion phase of transaction.
Auto-close-session :---------- possible values are true or false. If it is true session will be closed
automatically during the after completion phase of the transaction.
name
table
discriminator-value
mutable
dynamic-update
dynamic-insert
select-before-update
batch-size
optimistic-lock
lazy
id
property
set
map
list
joined subclass
discriminator
many-to-one
one-to-one
attributes :-------------------
name attribute allows you to specify fully qualified java class name of persistence class.
Table attribute allows you to specify the name of the database table.
Discriminator –value allows you to specify the value that differentiates individual subclass.default
value is class name..
Mutable :-------- this attribute specify that whether instance of the persistence class are mutable or
immutable. Possible value are true/false. Default value is true .because of true all the instances of
persistence class are mutable.(can be changed) use false to make the instances immutable(read only).
Dynamic –update :----------------- this attribute specify that update sql statement should be generated
at run time and contain only those column whose values are changed. Possible value are true/false
default value is false. When you enable this is true, update sql statement will be generated at run time
and contains only those columns whose value are changed.
Dynamic-insert :---------- possible values are true/false. Default value is false. When you enable this
insert sql statement will be generated at runtime and contains only the columns whose values are not
null.
Select-before-update :-------------- possible values are true/false .default value is false . when you
enable this hibernate will perform extra sql select to determine whether update is really required when
values are modified then only hibernate performs the update statement. (this attribute specify that
hibernate should never perform sql update unless object is actually modified.
Batch-size :------------- you should provide the integer values for this attribute. specifies the batch size
for fetching instances of this class by identifier default value is 1.
Optimistic-lock specifies the optimistic locking strategy. Possible values for this are none, version,
Dirty, all. Default value is version.
Lazy:----------- possible value are true/false. default value is true . this attribute is used to enable or
disable the lazy loading. If lazy =”true” then lazy loading will use internally. If lazy =”false” then lazy
loading will disable and aggressive loading will use internally. This attribute allows you to enable the
aggressive loading by specifying the value as false.
Entity name :------- a logical name which will be used to identify the persistence object default is the
class name.
Following are the list of sub elements of class element :---------------------
<id> <subclass>
<composite-id> <one-to-one>
<property> <one-to-many>
<set> <joined-subclass>
<map> <timestamp>
<list> <array>
Id element: --Id element will be used to declare the primary key column of the database table.
Attributes: ------------
Name
Type
Column
Unsaved-value
Sub element: -------
Generator
Name attribute allows you to specify name of the field in the persistent class.
Type attribute allows you to specify hibernate data type.
Column attribute allows you to specify name of the primary key column.
Unsaved-value: ------------ possible values are null, any name, undefined. This is used to differentiate
newly created instance from detached instances.
Sub element: ----------------- generator elements
Generator element is used to specify the primary key generator algorithm.
Generator will have one attributes called class for this class attribute you can specify any hibernate
built-in primary key generation algorithm also or you can specify your own primary key generation
algorithm also.
Attributes: ---------
Class
Sub element: --------
pram
Class attributes allow you to specify some generator class which is responsible for generation unique
identifiers for the instances of persistence class.
Hibernate provides various built-in primary key generation algorithm as listed below: -----------
• increment • guid
• identity • native
• sequence • assigned
• hilo(high low) • select
• seqhilo (sequence high low) • foreign
• uuid • sequence-identity
Increment :----------
This algorithm generates identifier of type short, int, long.
You shouldn’t use this algorithm for other data-types.
It starts the generating value from 1 and increment by 1.
Don’t use this algorithm in clustered environment.
<generator class=”increment”/>
Identity: ----------------
Algorithm generates identifiers of short, int, long.
This algorithm is supported by DB2,Sybase,ms SQL server, MYSQL and hyper sonic SQL(open
server like mysql).
This can be used in clustered environment.
<generator class=”identity/>
Sequence: -----------------
This algorithm generates an identifier of short,int,long.
This algorithm is supported by DB2,Oracle,SAPDB.
This algorithm uses sequence which is already created in the database.
Create table student{
Sid char(5);
Sname char(10); );
Create sequence sid-seq
Start with 101
Incement by 1;
Insert into student valies(sie-seq.nextval,”rajiv”);
Class=”sequence”
<id name=”sid” column =”sid” type=”int”>
<generator class=”sequence”>
<parameter name=”sequence”>sid-seq</param>
</generator>
<property name=”sname” column=”sname” type=”string”/>
hilo and seqhilo: -------
Hilo algorithm uses value generation for int, short and long.
This algorithm allows you to specify the high and low values.
This algorithm generates identifiers that are unique only for a particular database.
Seqhilo is similar to hilo but uses a sequence instead of table .
To use hilo_algorithm you should create a table with the name hi_value and
column next_value.
hilo :-----
<id name =”sid” column=”sid” type=”int”>
<generator class=”hilo”>
<param name=”table”> hi-value</param>
<param name=”column”> next-value</param>
<param name=”max_low”> 100</param>
</generator>
</id>
seqhilo :-----
<id name =”sid” column=”sid” type=”int”>
<generator class=”seqhilo”>
<param name=”sequence”>hi_val</param>
<param name=”max_low”> 100</param>
</generator>
</id>
uuid: -------
• uuid algorithm generated identifiers of type string.
• The identifier generated is unique with in the network because it uses Ip address of the machine while
generating id.
• This is not suitable for clustered environment.
• The id generated contains Ip address ,startup time of the JVM ,system time in the JVM, system time
and counter value (value which is unique with in the JVM).
• The generated id is enabled as string with Hexadecimal digits of length 32.
• This algorithm uses 128 bit network IP address + time stamp to generate the id.
Guid :------------- uses database generated quid string on ms SQL server and MySQL.
Native :-------- native algorithm uses one of the following three algorithms depending on the capabilities of
the database:------------
Idenbtity
Sequence
Hilo
<composite-id>
Attributes :-----------
Name
Class
Attribute of key-property:---------------
Name
<composite-id> // class=”primary key”
<key-property bname=”bid”/>
<key-property name=”sid”/>
</composite-id>
Attributes :------------
Column
Type
No sum elements.
Update attribute specifies that mapped columns must be included in update statement. Possible values are
true/false. Default value is true.
Insert :----------- attribute specifies that mapped column must be included in insert SQL statement possible
value are true/false. Default is true.
Lazy:------------------- possible values are true/false. Default value is false. When we enable this by writing
lazy=”true” then lazy loading will be applied
Unique :----------- possible value are true/false.
Default is false.
Not-null :--------possible value are true/false. Default is false.
Unique attribute enables the unique constraints on the column and not null enable the not-null constraint on
the column.
<many-to-many> and <one-to-many> tags are used only with the set tag.
Many-to-one: -----------------------
Association to another persistent class is decalred using many to one element. In this foreign key in one table
is referring the primary key of other tables.
Attributes :-----
Name
Column
Class
Cascade
Fetch
Update
Insert
Unique
Not null
Optimistic-lock
Lazy
Not-found
Cascade attribute specifies which operation should be cascaded from the parent object to associated object.
Fetch attribute decides to use either outer join fetching or sequencial select fetching.
Possible values are join or select.
Default value is select.
Not found :------------- possible value are ignore/exception. Default is exception. This attribute is used to
specify the action when a particular row is missing.
One-to-one :------------------------
One-to-one association from one persistent class to another persistent class is decalred using one-to-one
element.
Attribute :-----------------
Name
Class
Cascade
Fetch
Lazy
[II] org.hibernate.session
Hibernate transaction management depends on the following two existing transaction management :--------
JDBC transaction Management
JTA transaction management
The following piece of code you need to write to manage the transaction in JDBC :-------------
Connection con=null;
try
{
con=DBUtil.getConnection();
con.setAutocommit(false);
----------- --------------- -------------
----------- ---------------- --------------
con.commit();
}
Catch(Exception e)
{
con.rollback();
}
In JDBC transactional boundaries will be specified by developer only with the help of connection
interface.
JDBC transaction model is suitable for local transaction only i.e. we can manage a transaction on
single database only.
In the case of concurrent transaction we need to specify the isolation level which can be done with the
following method :-----------------
con.setTransactionIsolation(int);
The following property we can use to specify the transaction isolation in hibernate:---------------
<property name=”hibernate.connection.isolation”>n</property>
Where n=1 or 2 or 4 or 8
When you are implementing translation in your application you should thoroughly check about your
database. Whether it is supporting the transactions or not.
Some database may not support transaction for complete information you need to go through the
database manual or contact your database administrator(DBA).
You also need to verify the default isolation level of the database you are using. Because different
databases will use different isolation level as default. For example :------------------
Oracle :---------------- read.commited
Mysql :--------------- repeatable-read
About transaction
About local transaction and distributed transaction
About ACID properties
About transactional concurrency problem
About isolation level.
In hibernate we can do the persistent operations like insert(using save method),update(using update
method) and delete (using delete method).
In addition to the above methods we need to select the data from database. This can be done using the
following ways.
a) You can load the persistent object using load method when you know the identifier of the
object.
b) You can use sql queries to select multiple data from database.
c) You can use query language supported by hibernate to load the data from database.
Org.hibernate.Query :------------------
Interface query
{
Org.hibernate.criteria :------------------------
Interface criteria extends criteriaSpecification
{
Org.hibernate.criteria package
Restriction
Exception
Order
SQL :------------
String sql=”select * from customer”;
Rs=st.executeQuery(sql); // rs process
HQL :---------------
String sql = “from customer”;
Query q= ses.createQuery(sql);
List l=q.list(); // l process
QBC :---------------
Criteria ct=ses.createCriteria(customer.class);
List l=ct.list(); // l process
SQL:-----------
String sql=”select * from customer where fname=’”+fn+”’;
rs=st.executeQuery(sql);
HQL:-----------
QBC :-------------
Pagination :--------------------
Sometimes when you are displaying the results to the user you can display some results in one page,for
example 20 records and providing next and previous options to see the next 20 records and previous 20
records. This kind of implementation is called pagination.
In JDBC there is no direct support for the pagination concept as a developer you need to implement the
complete code for this.
In hibernate query interface & criteria interface contains the following to match:-----------
Query setFirstResult(int);
Query setMaxResults(int);
Criteria setFirstResult(int);
Criteria setMaxResults(int);
Display all the candidates information who are staying in mathikere on experience as 3 year. Display
25 record per page.
HQL :---------
list l=ses.createCriteria(Condidate.class)
.add(Expression.and(Expression.eq(“location”,mathikere”),Expression.eq(“exp”,newInteger(3)))
.setFirstResult(1)
.setMaxResult(2,5)
.list();
Display all the candidates information whose name is studying with sri, who are staying in Bangalore
and whose experience is 3-5 years.
HQL: --------------
List l=ses.createQuery(“from candiadate c where c.Cname like: cn and c.city=:city
And c.exp>=:exp1 and c.exp <=exp2”)
.setString(“cn”,cn)
.setString(“city”,city)
.setInt(“exp1”,exp1)
.setInt(“exp2,exp2)
.list();
QBC :-----------------
List l=ses.createCriteria.class)
.add(expression.and(expression.and(expression.like(“cname”,sri),expression.eq(“city”,”Bangalore”);
Expression.between(“exp”,newInteger(3),newInteger(5)))
.list();
Display top1 candidate among all the candidate whose experience is greater than 3 year.
HQL :-----------
candidate c=(candidate)ses.createquery(“from candidate c where c.exp>3)
. .uniqueResult();
QBC :---------------
Candidate c=(candidate)ses.createCriteria(candidate.class)
.add(Exception.get(“exp”,newInteger(3)))
.uniqueResult();
Candidate persist class has 2 subclass. One is fresher candidate,2nd is exp candidates.
How can I get the entire fresher and experience candidate.
HQL: -------------
List l=ses.createQuery(from candidate c”)
.list();
When we load the subclass, automatically subclass will be loaded.
End