• No results found

Can we specify different Isolation Levels for Transaction running in JDBC Application ?

In document Hibernate Notes (Page 32-39)

1 Specifying the Transaction Boundaries

Q. Can we specify different Isolation Levels for Transaction running in JDBC Application ?

Ans : No

Q. Can we specify different Isolation Levels for Transaction running in JDBC Application ?

Ans : Yes

Dirty

Read RepeatableRead PhantomRead Lock Type Concurrency

READ_UNCOMMITED No No No Not Lock R

e d u c e

READ_COMMITED Yes No No Column

REPEATABLE_READ Yes Yes No Row

SERIALIZABLE Yes Yes Yes Table

JDBC Hibernate JPA EJB2/EJB3 Spring

Local Tx. Yes Yes Yes Yes Yes

Distributed Tx. No No (Non-CME)Yes (CME) No (Non-CME)Yes (CME) Yes Yes

Flat Tx. Yes Yes Yes Yes Yes

Nested Tx. No No No No Yes

Query Language Supported by Hibernate : 1. HQL (Hibernate Query Language)

2. QBC (Query By Criteria) 3. QBE (Query BY Example) 4. Native SQL Queries 5. Named SQL Queries

Hibernate Query Language (HQL) :

Hibernate Query Language (HQL) is extremely powerful query language. HQL is much like SQL and are case-insensitive, except for the names of the Java Classes and properties. HQL is used to execute queries against database. Hibernate automatically generates the sql query and execute it against underlying database if HQL is used in the application. HQL is based on the relational object models and makes the SQL object oriented. HQL uses Classes and properties instead of tables and columns. HQL is extremely powerful and it supports Polymorphism, Associations, Much less verbose than SQL.

Why to use HQL?

Full support for relational operations: HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns.

Return result as Object: The HQL queries return the query result(s) in the form of object(s), which is easy to use. This elemenates the need of creating the object and populate the data from result set.

Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any.

Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the applications.

Support for Advance features: HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.

Database independent: Queries written in HQL are database independent (If database supports the underlying feature).

Understanding HQL Syntax

Any Hibernate Query Language may consist of following elements: Clauses

Aggregate functions Subqueries

Clauses in the HQL are:  from

 select  where  order by  group by

Aggregate functions are:

 avg(...), sum(...), min(...), max(...)  count(*)

 count(...), count(distinct ...), count(all...) Subqueries

Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the underlying database supports it.

Hibernate Cache ---

Cache is representation of Database near to Application. When we cache the Read mostly data, we can reduce the No. of round trips between our application server and database server which increases performance of our application.

In general, we can have 3 types of cache scopes : 1. Trancational Scope Cache

2. Process Scope Cache 3. Clustered Scope Cache.

Trancational Scope Cache : This kind of cache will created whenever the Transaction is started and Runs as long as Transaction is running. Transactional scope cache will be destroyed whenever the Transaction ends either by commit or by rollback.

Process Scope Cache : This kind of cache can be accessed by multiple Transactions running in the Application or process.

Clustered Scope Cache : When our enterprise application is large scale application then we must use cluster environment where multiple servers will be clustered and integrated with LBS (Load Balancing Server) for routing the requests. In the case of Clustered Scope Cache, when one node caches the data then same data will be replicated to other nodes automatically.

Fig. : Hibernate Cache Architecture First Level Cache :

* When we create a Transaction then we have to process more tasks like :  Configuration

 openSession  create Transaction

 call persistence class object  process all tasks like updation.

* Multiple persistence object store in SessionCache. When tx.commit() method will be invoked then all transaction store in database and flushing all session object and closing transaction and all. * Tasks are :

1. Session cache is the first level cache.

2. Session cache is the Transactional Scope Cache.

3. Session cache is enabled by default and should not be disabled.

4. Whenever we insert or update or select or delete the records then those persistence objects will be placed automatically in session cache.

5. We can remove the persistence object from session cache using – evict(obj) & clear() Second Level Cache :

 Query Cache is the second level cache.

 Query Cache can be process scope or cluster scope cache.

 Query Cache is disabled by default. You have to enable explicitly if required.

 Whenever we execute the Hibernate queries (HQL, QBC etc. – select sql statement) then all the records returned by select statement will be placed in query cache.

Steps to implements Query Cache : ---

1. Enable the query cache by writing the following property in hibernate configuration doc. <property name=”hibernate.cache.user_query_cache”>true</property>

2. Specify the Required cache provider in hibernate configuration doc.

<property name=”hibernate.cache.provider_class”>org.hibernate.cache.EhCacheProvider

</property>

Note : Cache provider supported by Hibernate : 1. HashTableCacheProvider

2. EhCacheProvider (for small application) 3. OSCacheProvider (not mostly use) 4. SWarmCacheProvider (not mostly use) 5. TreeCacheProvider (Jboss Cache Provider)

3. Specify the required caching concurrency strategies in Hibernate mapping doc. <cache usage=”xx”>

Usage value can be one of the following :

i> read-only ii> nonstrict-read-write iii> read-write iv> transactional Note : We have to specify the caching concurrency strategies for class, Collections and

Associations.

Example : class Student{ int cid;

String cname; Set emails; --- }

<class name=”Student” table=” Student”> ---

<cache usage=”read-only”/> <property name=”cname”/>

<set name=”email” table=”emails”/> <cache usage=”read-only”/>

--- </set>

</class>

4. Call setCacheable() method with true value on Query or Criteria or SQLQuery objects. HQL

Query q=session.createQuery(“from Customer”); q.setCacheable(true); List list=q.list(); QBC Creteria ct=session.createCriteria(Customer.class); ct.setCacheable(true); List list=ct.list();

5. Specify the Storage Implementations and Expiration Policies. Note : This will change from cache provider to provider.

ehcache.xml (place in src folder)

<ehcache>

<diskstore path=”java.io.tmpdir”/>

<defaultcache maxElementsIsMemory=”100” eternal=”false”

timeToIdleSeconds=”120” timeToLiveSeconds=”120”

overFlowToDisk=”true”/>

<ehcache name=”helloCache”

maxElementsIsMemory=”10” eternal=”false” timeToIdleSeconds=”300”

timeToLiveSeconds=”600” overFlowToDisk=”true”/>

Caching Concurrency Strategies ---

There are four Caching Concurrency Strategies : * Read-only

* non strict-read-only * read-write

* transactional

 This strategies will allow us to apply the required locking mechanism for the persistence objects. Which are available in Query cache.

 In this case of Process Scope or Clustered Scope Cache, one persistent object can be accessed by multiple Transaction running con-currently. This may leads to some concurrency problems like Dirty Read Problem, Repeatable Read Problem and Phantom Read Problem.

To avoid the problems, we have to required Transactional Isolation Levels as shown in Table :

Hibernate Caching Concurrency Strategies :

Concurrency

Strategy CME Non CME

Supports UNCOMMITED Supports COMMITED Supports Read Supports Serializable

Transactional Yes No Yes Yes Yes No

Read-write Yes Yes Yes Yes No No

Non-Strict-

read-write Yes Yes Yes No No No

Hibernate Caching Providers : Cache provider Class Storage Type Query Cache Support Read only Cluster type Non strict Read only Read

Write Transactional CME Non CME Production Support Flash Table cache provider

Memory Yes Yes No Yes Yes No Yes Yes No

Eh cache

provider Memory Yes Yes No Yes Yes No Yes Yes Yes

O cache

provider MemoryDisk Yes Yes No Yes Yes No Yes Yes Yes

Swarn cache

provider Clustered No Yes Yes Yes No No Yes Yes Yes

Tree cache

provider Clustered Yes Yes Yes No No Yes Yes No Yes

Filter :

Hibernate3 provides an innovative new approach to handling data with "visibility" rules. A Hibernate

filter is a global, named, parameterized filter that can be enabled or disabled for a particular

Hibernate session.

Hibernate3 has the ability to pre-define filter criteria and attach those filters at both a class level and a collection level. A filter criteria allows us to define a restriction clause similar to the existing "where" attribute available on the class and various collection elements. These filter conditions, however, can be parameterized. The application can then decide at runtime whether certain filters should be enabled and what their parameter values should be. Filters can be used like database views, but they are parameterized inside the application.

In order to use filters, they must first be defined and then attached to the appropriate mapping elements. To define a filter, use the <filter-def/> element within a <hibernate-mapping/> element: <filter-def name="myFilter">

<filter-param name="myFilterParam" type="string"/> </filter-def>

This filter can then be attached to a class: <class name="myClass" ...>

...

<filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/> </class>

<set ...>

<filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/> </set>

Or, to both or multiples of each at the same time.

The methods on Session are: enableFilter(String filterName), getEnabledFilter(String filterName), anddisableFilter(String filterName). Filters must be enabled through use of the Session.enableFilter() method, which returns an instance of the Filter interface. If you used the simple filter defined above, it would look like this:

session.enableFilter("myFilter").setParameter("myFilterParam", "some-value");

Methods on the org.hibernate.Filter interface do allow the method-chaining common to much of Hibernate.

 Filter is an Interface available in org.hibernate package.

 Hibernate filters are defined in Hibernate mapping documents (hbm.xml file)-which are easy to maintain.

 One can programmatically turn on or off the filters in the application code.  Filters can't be created at run time.

By default, filters are not enabled for a given session.

 Sometimes it is required to only process a subset of the data in the underlying Database tables. Hibernate filters are very useful in those situations.

We can attach a single filter to more than one class or collection. To do this, you add a <filter> XML element to each class or collection. The <filter> XML element has two attributes viz. name and condition. The name references a filter definition (in the sample application it's : statusFilter) while condition is analogous to a WHERE clause in HQL.

Note: Each <filter> XML element must correspond to a <filter-def> element. It is possible to have more than one filter for each filter definition, and each class can have more than one filter. Idea is to define all the filter parameters in one place and then refer them in the individual filter conditions.

In the java code, we can programmatically enable or disable the filter. By default the Hibernate Session doesn't have any filters enabled on it.

The Session interface contains the following methods:  public Filter enableFilter(String filterName)  public Filter getEnabledFilter(String filterName)  public void disableFilter(String filterName)

The Filter interface contains some of the important methods:  public Filter setParameter(String name, Object value)

 public Filter setParameterList(String name, Collection values)  public Filter setParameterList(String name, Object[] values)

setParameter() method is mostly used. Be careful and specify only the type of java object that you have mentioned in the parameter at the time of defining filter in the mapping file.

The two setParameterList() methods are useful for using IN clauses in your filters. If you want to use BETWEEN clauses, use two different filter parameters with different names.

---

In document Hibernate Notes (Page 32-39)