1

April 11

getCurrentSession or openSession - a sessionic dilema

Posted by Ajay

Our hibernate code uses two different types of functions to access the session. openSession() and getCurrentSession(). But then I have always wondered the major difference between them. Now that I realized the difference, it is time to share it with the world.

First let’s talk about sessions in Hibernate.Session is defined as a unit of work. Work begins by starting a session and ends by closing a session.

A Transaction can also be defined similar to a session. But a transaction applies to databases. One kind of transaction works in auto commit mode, where there is one short transaction per SQL statement. Hibernate usually disables auto commit mode. A single Hibernate session has the same scope as a transaction. The most common model used is a session per request model where a single session/database transaction is executed for every request coming in from the client.

session per request

session per request

Multi step dialogs like wizards are implemented as session per conversation where a single session includes multiple transactions.

session per conversation

session per conversation

A session is opened whenever getCurrentSession() is called for the first time. This creates a brand new session if one does not exist or an existing one if one alrady exists. In tomcat this associates a session with a thread which is created using the underlying ThreadLocal object. But since Tomcat uses thread pooling it is entirely possible that a request may receive a thread with a session already associated with it, thus introducing the possibility of not even creating a brand new session. The method openSession() on the other hand creates a new session but does not attempt to associate it with a thread. But remember openSession() introduces another hitch in that it expects users to handle the closing and flushing of sessions themselves, instead of letting Hibernate do it automatically for us.

This is one of the advantage of using a JTA enabled container since JTA container will handle the session by binding it to a transaction instead of a thread like it happens in a Tomcat environment without JTA which essentially uses JDBC transactions.

References

http://www.hibernate.org/42.html

Tags:

 
0

December 17

Grizzly Comet - what’s grizzling with comet?? - Part 1

Posted by Ajay

I have been working on implementing an interesting application to manage all the  photographs (I will talk more about this project in a later post). In the process, I have been thinking about a feature I want to add to my application which involves alerting users using my web application to be alerted as and when new additions are made to my photo repository. I came across Grizzly Comet and felt an inane desire to try this out on my application, so here is my technical knowledge sharing about this experience

Let’s talk NIO

Before we talk about Grizzly and Comet, let’s try to understand where this whole concept started. Java 1.4 introduced a collection of Java programming API’s called New I/O with features for intensive I/O operations and was developed as part of JSR 51. The main purpose of NIO is to have an implementation that would allow use of the more efficient underlying platform implementation of I/O. A single thread can operate on a bunch of connections instead of having one thread per connection, which provides high degree of performance. This API provides variety of features that include buffers for primitive data types, character set encoders and decoders, pattern matching features, channels. Details about NIO is probably for another post.

Introducing the “Comet” philosophy

Another interesting concept is what is called Comet application model. The basic idea is that a web server would push HTTP data to a browser without the browser requesting the data. The Comet approach typically uses Ajax with long polling to achieve it’s task.

A simple diagram to illustrate the Comet methodology as opposed to the web application model is as below

Web applications have evolved through various stages, as depicted in the following diagram

In the Page by page model, that most web applications started off from and a model that many still follow, every new browser page would send a request to the web server. So essentially we had to refresh the whole page every time a small bit of data on the page changed, which started to become a real pain.

Thus began the era of Ajax where any new information would take the form of Ajax requests to the server to update the web page asynchronously. Web apps would poll the servers periodically for new information, but still the point of the matter is that users have to periodically hit the server to request information.

Finally Netscape introduced the concept called web server push that has evolved into the comet programming model.  Essentially imagine having the benefit of server to client messaging without issues of fat clients.

Imagine a real time event like a baseball game or the stock market scenario, when users would want to be kept informed of events happening during the game or certain stock market events. Such scenarios cannot be implemented using traditional web application methodologies. This is where Comet or Reverse Ajax methodologies fit in.

Comet is a collection of technologies that provides the functionality of web server push through persistent HTTP connection. Comet can be implanted using Streaming where the browser opens a single persistent connection to the server for all server events or long polling.  Many applications use the comet model, some of them include Meebo, Gmail chat, Jotspot, ICEFaces JSF framework. The Comet approach involves a departure from the usual web based platform approach. It may involve storing some kind of state information about the clients who wish to receive notifications on the server., similar to messaging systems. This is the reason most Comet based approaches rely on custom adapted application servers. In Java Jetty and Grizzly have support for Comet based approaches. This type of design is also being introduced through the continuation concept in other platforms. But how does the browser itself stay in contct with the server applications? Some approaches include long polling, dynamic script tags and Iframes which are all non standards. Many client side Comet designs rely on frameworks to iron away incompatibilities, Dojo for example is an Ajax/Comet implemntation

What is Grizzly?

Writing scalable server application has been a big task always. Threading issues caused issue with scaling. This prompted Grizzly to make it’s appearance. It is a HTTP Connector  based on NIO that ships with Glassfish. It is designed to replace Apache Tomcat’s Coyote connector. All Java based web connectors have scalability limited by the number of available threads.  This is where Grizzly improves by providing plug ability of any kind of thread pool.

Grizzly essentially is based on a task based architecture where each task represents an operation. Every task executes on it’s own thread pool or a shared one. The main entry point is Pipeline which has nothing in common with the Catalina Pipeline. The Grizzly Pipeline is essentially a Thread Pool Wrapper and is responsible to execute a task.  The SelectorThread is another important component where the NIO selector is created.  When processing a request, the SelectorThread will create Task instances and pass it on to the Pipeline. There are three types of Tasks - Accept Task - to handle NIO OP_ACCEPT, ReadTask/AsyncReadTask/ReadBlockingTask - to handle OP_READ, Processor Task - to handle OP_WRITE. This SelectorThread can either create one Pipeline per Task or share a Pipeline among tasks.

Grizzly has introduced Comet support and is implemented on top of the Asynchronous Request Processing extension of Grizzly.

So thats that for my technical sharing session for today, in my next post I will give a brief intro to the Comet API and talk about how I used it in my project. Ciao, for now!

References

http://alex.dojotoolkit.org/2006/03/comet-low-latency-data-for-the-browser/
http://weblogs.java.net/blog/jfarcand/archive/2005/06/grizzly_an_http.html
http://www.pathf.com/blogs/2006/06/infrastructure_/
http://searchsoa.techtarget.com/tip/0,289483,sid26_gci1301487,00.html
http://weblogs.java.net/blog/jfarcand/archive/2006/01/introduction_to.html

Tags: , ,

 
2

October 22

To JPA or not - an introspection on the Java Persistence API

Posted by Ajay

One fine day I was looking into the object persistence architecture we utilize in my project. We use a simple Hibernate based persistence, connecting to our database through JDBC, using JDBC’s transaction semantics. Then i came to thinking is there any advantage of using JPA over Hibernate as opposed to plain old Hibernate. Here are some of my thoughts. Let me start off by talking about persistence, hibernate and JPA in general.

What is persistence?

The general idea behind persistence is to extend an object’s life span. There are technically many ways to implement this. A simple way is to simply store the object as a file on the disk and then convert it back into an object, a good example of this is persisting objects as XML. Another alternative is using a database to store the data. The decision on which kind of persistence to implement basically depends on the kind of functionality that you need to implement. In my project we use both database based persistence and file based persistence (we use XStream , which is again a story for another day)

Let us consider persistence with a database perspective. Traditionally databases follow a relational paradigm. A Table is the main actor and is related to other tables through a relation. But an Object on the other hand compromises an entity along with methods that operate on the entity and it’s association with other entities. This has led to an object relation impedance mismatch which makes it tough to convert between those two.
Say hello to Hibernate and JPA!!

Hibernate has filled this void albeit not perfectly but enough to do the job. Persistence frameworks
is the key behind object relational mapping. Hibernate so far used to do persistence with it’s own Core API. EJB 2.1 was on the wane, a bloated technology, losing it’s grandeur, then came the redesign and scripting of a new reign of a new technology, EJB 3.0 specification that provided the JPA specification as it;’s answer to the entity beans of old.  Hibernate 3.0 has to adapt to this changing world and adopted the JPA specs as it’s own.

JPA essentially provides a POJO based persistence model. It replaced entity beans which had the following problems:
- too heavyweight and coupled to the application server itself
- difficulty in deploying and unit testing

JPA essentially provides a standardization to the persistence methodology. Thus allowing any persistence framework to be used underneath JPA without having to worry about too much configuration. Hibernate implements the JPA specification by creating a wrapper over the Hibernate Core. This wrapper can be further made more effective by introducing annotations to take out some of the responsibility of the configuration file.

When thinking about the JPA specs, we introduce Hibernate EntityManager which is used to define the JPA life cycle rules for persistent objects, and is used as a wrapper around HibernateCore. The advantage of using JPA is that it brings with it some portability when having to switch between application servers that support JPA, which may not be possible with a Hibernate based solution.

JPA has many components that can be somewhat mapped to Hibernate:
EntityManagerFactory –> SessionFactory,
Persistence class creates the EntityManagerFactory,
EntityManager –> Session,
Query –> Query,
EntityTransaction –>Transaction.

It only needs a persistence.xml in the  classpath which configures basic hibernate connection properties.
Everything else is managed through Annotations (for ex. a PersistenceContext injects a EntityManager object into the bean).

The advantage of using Hibernate with JPA is that you can enabled several features of Hibernate without having to mess with the  JPA configuration like for example a second level hibernate cache. In addition to this you can use native hibernate mapping and API,  the only problem with this is that if you decide to use a different JPA provider, it’s gonna get dirty.

Ex 1: If you want to export the schema programmatically, then use a Hibernate Ejb3Configuration()
that can easily replace the EntityManagerFactory, which can yield a AnnotationConfiguration that can
be passed into the SchemaExport instance.

Ex 2: Use the SessionFactory if you need programmatic control over the
second level caching. This can be done by fist casting EntityManagerFactory into
HibernateEntityManagerFactory and then extracting the SessionFactory.

But using JPA also has some disadvantages
* no control over cascading behaviour
* no indexed collections,
* Hibernate provides Filters and Caches
* no collections of primitive values

How useful would JPA be for me in my project?

This is an interesting question. One reason for the shift to JPA could be the standardization aspect, with increased portability. Now we no longer need to worry about moving to a different persistence provider like Hibernate or JDOLink, a concept called pluggable persistence providers. Now the question do I need it for my work? Is it worth sacrificing some of the features of hibernate like cascading and indexed collections for a standardized interface. For now i dont think so, but in the future if we decide to move to a full fledged application server like JBoss, most likely.

Some reference links for this particle post

http://asrijaffar.blogspot.com/2007/01/native-hibernate-vs-hibernate-jpa.html
http://maestro-lab.blogspot.com/2007/09/coding-java-persistence-jpa-vs.html
http://www.javaworld.com/javaworld/jw-07-2008/jw-07-orm-comparison.html
http://clarkupdike.blogspot.com/2007/01/hibernate-mappedby-to-superclass.html

Tags: ,

Copyright © 2010 “An Image of My Life” blog series All rights reserved. Theme by Laptop Geek.

Total hits: 38641