Anda di halaman 1dari 25

One to many relationship: ----------------

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.

For this you have to do the following things: -------


Declare the collection type education field in the Student class.
Use <set> tag inside the student.hbm.xml document.
Many-to-many relationship: --------------
Consider the scenario between book and author class. One book can have many authors and one author can
write many books this kind of relationship is called as many-to-many relationship.
This can implemented as bidirectional one-to-many relationship.
To implement bidirectional one-to-many relationship between Book and Author we need to do the following :
Add Authors field inside the book as a collection type
Add Book field inside the Author class as a collection type.
Use following set tag in Book.hbm.xml
<set name=”authors” table=”book_author”>
<key column=”bid”/>
<one-to-many column=”aid” class=”Author”/>
</set>
Use following set tag in Author.hbm.xml
<set name=”books” table=”book_author”>
<key column=”aid”/> // aid --------- author_id
<one-to-many column=”bid” class=”Book” inverse=”true”/> // bid -------- book_id
</set>

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.

Introduction to HQL(hibernate query language)


HQL is an object oriented query language which helps you to query the database.
Hibernate provider some other two types of query language also
 QBC(query by ceria )
 QBE(query by example )
• Among the three query language supported in hibernate HQL is more powerful.
• When you are writing the query in HQL, you going to specify the persistence class and fields in that
class in the query.
For example :--------- assume there is a movie table and movie persistence class .the following are some
possible query in HQL.:----------
Getting all the movies from the table:---------------
In SQL :-------
Select * from movie;
In HQL : -----------
From movie m; // persistence class name
Getting movie by name :----------------
In SQL : ------------
Select * from movie where mName=’x’;
In HQL : -----------
Fom movie m where m.movieName=? // persistence field
SQL HQL

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.

Application Cache Database


Webapp

Server some special area

JDBC ---------- you have to implement caching


EJB------------you have to implement caching.
Hibernate -------- built-in support for caching

Advantage of caching: -----------------


When you implement caching in your application it contains Read-mostly data which is already available
in the database. When application is trying to get the same data it can use cache memory instead of
interacting with the database. So, caching implementation reduces unnecessary network overhead between
application server and database server. This increases the application performance.

NOTE : ----------- implementation the caching technique for read mostly data only. Don’t implement for
write-mostly.

Types of cache scope :--------


 Transactional scope cache
 Process scope cache
 Clustered scope cache

Transactional scope cache: -------------


This kind of cache will be associated with single transaction

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

Hibernate cache architecture: ----------------------

First level cache

Session Cache

Second level Cache


Query Cache

Caching concurrency
Strategies Cache providers

Caching implementation Storage & Expiration policies

First level cache: ---------------


 Session cache is the 1st level cache.
 By default session cache will be ended by the hibernate system.
 Session cache should be ended & should not be turned off for various sessions.
 When you are trying to save the object or load the object or update the object then that object will be
stored in the session cache automatically.
 Session cache is the transactional scope cache.
SD Session Cache
Application First level cache
Tx Stu1

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(“abc@sd.com”);
// 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();

Second level cache: -------------------


Second level cache is clustered level cache.
Second level cache is pluggable cache. Based on your requirement you can enable or disable the second level
cache anytime.
Query cache is the second level cache.
When you execute any query it returns multiple records. if you want to cache all the records returned by all
the query. You need to enable query cache.
You need to enable the query cache separately for the persistent object, collection and association objects.

Steps to implement query cache :------------------------


Enable the query cache by writing the following property in hibernate.cfg.xml.
<property name=”hibernate.cache.use-query-cache”>true</property>
Specify the cache provider by writing the following property in hibernate.cfg.xml.
<property name=”hibernate.cache.provider-class”>org.hiberante.cache.OSCacheProvider</property>

Four types :-----------


EasyHibernateCacheProvider EhCacheProvider
OSCacheProvider
SwarmCacheProvider
TreeCacheProvider
If you want to cache any class objects you need to provide the following tag in the hibernate mapping
document:--------------
<cache usage=”x”/>

Here x can be :-------- caching strategies


Transactional
Read-write
Nonstict –read-write
Read only

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
}

Mapping will be :-----------

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.

Caching concurrency strategies :-------------


In the case of process level and clustered level cache multiple transaction can access the cache concurrently.
This gives instantaneous results.
Some problems when multiple transaction are accessing single cache are :--------
Dirty read problem
Phantom read problem
Repeatable read problem

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

Transactional strategies does not maintain fertilizable isolation level.

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:---------------------------

This strategies will be available in both the environments.


This strategy maintains only one isolation level called uncommitted

Read-only :--------------------
This strategy will be available in both the environments.
It does not maintain any isolation level.

Which caching strategy provides you the better performance.


Read-only.

CacheProvider types :--------------


There are four types of cache providers :---------------
 EhCachePrvider (Easy hibernate CacheProvider)
 OSCacheProvider (Open Symphony CacheProvider)
 SwarmCacheProvider
 TreeCacheProvider (JBOSCacheProvider)
EhCachePrvider: ---------------

1) EhCache implementation is limited to process scope.


2) EhCache supports query cache.
3) EhCache supports read-write, nonstrict-read-write and read-only caching strategies.
4) It does not support transactional strategies.
5) The provider class for this is org.hibernate.cache.EhCacheProvider.

OSCacheProvider

1) It is similar to EhCache.
2) The provider class for this is org.hibernate.cache.OSCacheProvider.

SwarmCacheProvider

1) This cache implementation will be possible only in the clustered environment.


2) It does not support query cache.
3) It supports read-only and nonstrict-read-write concurrency strategies.
4) It does not supports transaction and read-write.
5) The provider class for this is org.hibernate.cache.SwarmCacheProvider.

TreeCacheProvider or JBOSSProvider :----------------


1) This cache implementation will be possible only in the clustered environment.
2) TreeCacheProvider supports query cache.
3) TreeCache maintains read-only and transactional.
4) It does not support read-write and nonstrict-read-write concurrency strategies.
5) Provider class for this is org.hibernate.cache.TreeCacheProvider.

Program --------------------7 file

Hibernate with struts


Big program
20 file program
Hibernate configuration document

 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

List of properties: -----------------


1. hibernate.connection.driver-class
2. hibernate.connection.url
3. hibernate.connection.username
4. hibernate.connection.password
5. hibernate.connection.pool-size
NOTE: ------ when you are using third party connection pooling framework then only you have to specify
“hibernate.connection.pool-size” property.
Following are the some example of third party connection pooling framework: --------------
• Dbcp (Database connection pooling)
• C3P0
 C3P0 connection pooling framework will come by default along with hibernate libraries.
 The above mentioned connection pooling framework are suitable for development mode only and not
suitable for production system.
• When you specify the above properties, hibernate will obtain connections using Driver manager .
• Hibernate has built-in connection pooling mechanism which fills the pool with the JDBC connection
obtain using driver manager.
• Hibernates built-in connection pooling mechanism is not suitable for the production systems.
• C3PO is an open source JDBC connection pool distributed along with the hibernate. Hibernate will
use C#PO connection provider for connection pooling if you set “hibernate.C3PO.*” properties in
hibernate configuration document.
Example: -------------
Following example usage of of C3P0 connection pooling for Mysql database :-----------
<hibernate-configuration>
<session-factory>
<property name=”connection.driver-class”>con.mysql.Jdbc.Driver</property>
<property name=”connection.url”>jdbc:mysql://localhost/data</property>
<property name=” connection.username”>root</property>
<property name=” connection.username”>raman</property>
<property name=” hibernate.C3P0.min-size”>5</property>
<property name=” hibernate.C3P0.max-size”>500</property>
<property name=” hibernate.C3P0.timeout”>3505</property>
<property name=” hibernate.C3P0.max-statements”>50</property>
</session-factory>
</hibernate-configuration>

 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.

Hibernate dataSource properties

 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

Initial ContextFactory  connectionPool


providerUrl  dataSource
ds=(dataSource)ctx.lookup(jndi_name);
con=ds.getconnection();

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

• Provider-class is used to specify the custom class name of cache provider.


• Use_query_cache enables the query cache. Possible values are true/false. Default value is false.
• Use-minimal-puts optimizes second level cache option to minimize writes at the cost of more frequest
read
• Possible value are true/false.
• This setting is most useful for clustered caches.
• Default value is true.

• 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.

Other hibernate properties :----------------


 hibernate.dialect
 hibernate.show-sql
 hibernate.session-factory-name
 hibernate.max-fetch-depth
 hibernate.default-batch-fetch-size
 hibernate.jdbc.fetch-size
 hibernate.jdbc-batch-size
 hibernate.jdbc.use-scrollable-resultset
 hibernate.connection.provider-class
 hibrnate.connection.isolation
 hibernate.connection.autocommit
 hibernate.connection.release-mode

list of attributes in root element:----------------


package
auto-import
default-lazy
default-cascade

class element attribute

 name
 table
 discriminator-value
 mutable
 dynamic-update
 dynamic-insert
 select-before-update
 batch-size
 optimistic-lock
 lazy

sub elements :------------

 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

Remaining are not so much required.

<composite-id>

Sub element :------------


<key-property>

Attributes :-----------
Name
Class
Attribute of key-property:---------------
Name
<composite-id> // class=”primary key”
<key-property bname=”bid”/>
<key-property name=”sid”/>
</composite-id>

Dissimilar element :----------------


This element is required for polymorphic persistence using table per class instance mapping.

Attributes :------------
Column
Type

No sum elements.

Property elements :-----------------


No sub elements
Attributes :--------------------
Name
Column
Type
Update
Insert
Lazy
Unique
Not-null
Optimistic –lock

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

Sub elements :----------


Key
Element

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

Same sub element.


Hibernate API
[I] Org.hibernate.sessionFactory:-----------------
sessionFactory creates session
usually
an application has single sessionFactory per database.
sessionFactory is immutable
methods :---------------

[II] org.hibernate.session

Transaction support and looking mechanism in hibernate :--------------


The following piece of code will be used to managed the transaction in hibernate.
Transaction tx=null;
try
{
SessionFactory sf=HibernateUtil.getSessionFactory();
Session ses=sf.openSession()
tx.ses.beginTransaction();
Op1
Op2
Op3
Op4
tx.commit
ses.close();
}
catch(Exception e)
{
tx.rollback();
}

Hibernate transaction management depends on the following two existing transaction management :--------
JDBC transaction Management
JTA transaction management

JDBC transaction management: ----------------------------


 In JDBC transaction will be started with connection resource as follows :--------------
Con.setAutocommit(false);
 In JDBC we can end the transaction with one of the following two method available in connection
interface :------------------------
Con-commit();
Con.rollback();

 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);

JTA transaction management: ------------------------------


 JTA stands for java transaction API ,whose implementation is available only in container and
environment, i.e. we can use JTA transaction management when we are working with any of the
application server available in market.
 JTA transactions will be implemented inside the EJB components in two ways :-------------
CMT(container managed transaction)
BMT(Bean managed transactions)
 In the case of JTA, transaction boundaries will be specified by either developer or container.
 The following piece of code you need to write the specify the transactions in EJB.
UserTransaction ut=null;
Try
{
ut=sc.getUserTransaction(); // sc SessionContext
ut.begin();
Op1
Op2;
Op3;
ut.commit();
}
Catch(Exception e)
{
ut.rollback();
}
Choosing the transaction model in hibernate :--------------
 JDBC supports only local transaction where as JTA supports distributed transactions.
 JDBC transaction management can be used in non-container environment(outside the application
server)where as JTA transaction management can be used in container management environment .
(inside the application server).
 In hibernate the default transaction model is JDBC.
 If you want to use JTA ,you need to specify the following property in hibernate configuration
document :----------
<property name=”hibernate.transaction.factory-class”>
Org.hibernate.JTATransactionFactory</property>

 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

Basic concept you need to remember: ----------------

 About transaction
 About local transaction and distributed transaction
 About ACID properties
 About transactional concurrency problem
 About isolation level.

Locking mechanism in hibernate :------------------------


 Locking is a process of acquiring lock on database by the transaction.
 We can see two types of locking in general :-------------------
Optimistic locking
Pessimistic locking
a) In the case of optimistic locking, when one transaction will be held until the transaction complete . at
this time the other concurrently running transactions are unable to read or write the data from the
locked row/column.
b) In the case of optimistic locking when a transaction acquires a lock on row/column, other
concurrently running transaction can read the data but cannot update the data.
 Hibernate supports only optimistic locking
 Optimistic locking is not recommendable always use only when it is really required. Because it is not
scalable.
 We can apply the desired lockmode with the help of constant defined in lockmode class.
1) LockMode.NONE :--------- this represents absebce of lock.
2) LockMode.READ :------------- this mode aquires the lock automatically when hibernate reads
the data under repeatable read or serialization isolation level. In this lock may be required
explicitly by the user request.
3) LockMode.write :------------ this acquires lock automatically when hibernate updates or inserts
a row into the database.
4) LockMode.UPGRADE :------------------- in this lock will be acquired upon explicit user request
using select for update on database which support that syntax.
5) lockMode.UPGRADE_NOWAIT:----------- in this lock will be acquired upon explicit user
request using select …… for ------update _nowait under Oracle .
 you can get the existing lockmode using the following method :---------------------------
lockMode getCurrentLockMode(Object o);
 we can set the desired lockMode using the following method which is available in query and
criteria :---------
void setLockMode(lockMode);

Query Language support in hibernate: --------------

 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.

Query Language supported by hibernate: -------------


HQL(hibernate query language)
QBC(query by criteria)
QBE(query by Example)

Org.hibernate.Query :------------------
Interface query
{

Org.hibernate.criteria :------------------------
Interface criteria extends criteriaSpecification
{

Org.hibernate.criteria package

Restriction

Exception
Order

Selecting all the rows from customer table :---------

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

Get all the customer information whose first name is srinivas .

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 :---------

Query q=ses.createQuery(from candidate c where c.location=:loc and c.exp=:exp”);


Q=q.setString(“loc”,mathikere”);
Q=q.setInt(“exp”,3);
Q=q.setFirstResult(1);
Q==q.setMaxResults(25);
List l=q.list();
Or Named Query
List getCondidates(string loc,int exp,int m,int n)
{
List l=ses.createQuery(“from candidate c --------------“)
.setString(“loc”,loc)
setInt(“exp”,exp)
.setFirstResult(m)
.setMaxResults(m)
.list();
Return l;
}

Some requirement using position/parameters:------------


HQL:----------------------

List l=ses.createQuery(from candidate c where c.location=? and c.exp=?”) // ? is positional parameter


c.setString(1,“matikere”)
.c.setInt(2,3)
c.setFirstResult(1)
c.maxResults(2,5)
c.list();

some requirement using QBC

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();

Polymorphic Query: -----------------

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.

Display all the records from all the table in database.


List l=ses.createQuery(“from Object o)
.list();
Display all the records from all the tables where corresponding persistence class are eligible for serialization.

List l=ses.createQuery(“from serializable”).list();


Display all the candidates information by experience wise in descending orders.
List l=ses.createQuery(“from candidate c order by c.exp desc”)
.list();
List l=ses.createCriteria(candidate.class)
.add(Order.desc(“exp”))
.list();

End

Anda mungkin juga menyukai