Monthly Archives: March 2009

Java Persistence API Concepts

There are many object relational mapping (ORM) tools available in licensed as well as freeware category. You must have heard Hibernate and Toplink in open source technologies. These technologies offer their own implementation to interact with database. Though the implementation varies, the underlying business is same – map an object in middle tier with a relation in database. Java Persistence API (JPA) selects the necessary and best out of these open source frameworks, and defines a specification so that the application server vendors can comply with that. Also, the open source technologies are registering their support to with JPA. In this article, we understand the terminologies of JPA, and how the middle tier object is linked with a database table. If you have already worked on any ORM tool, then this will be a cake walk for you, just that there will be difference of words.

Interaction with Database:

Whenever any application interacts with database, it has to go through following steps -

  • Make a connection with database
  • Transform the middle tier objects into query and persist in database and vice versa
  • Manage the interaction session with database

Each of these step needs to be implemented by a developer by choosing one of the multiple options available. Let us take each of above step, and see what all options we have without JPA.

Make a Connection to Database:

Basically, it is opening a session with database using appropriate driver, connection url, user and password. Complexity of this does not end here. Connection is actually a resource, and we need to be careful while dealing with it. Hence there are multiple ways of creating and managing connection.

  • Using JDBC API programmatically to manage the connections (pool)
  • Using application server data sources
  • Using session factories provided by ORM tools

Transform Middle Tier Objects:

There are two options for this – since ages, we have been converting the object data into queries and then firing those queries on database. With ORM tools availability, we started mapping the table columns with object attributes (along with relations) in xml formats. ORM tools used these xmls and generated queries for us. No need to learn SQL and other database languages.

Manage the Session with Database:

In other words, manage transactions. Use JTA, application server support or the ORM tool support to transaction management. Frameworks like Spring also provide container to do the data access business as well as manage transactions declaratively.

 

How JPA Wants Us to Do Above Steps?

As stated above, JPA selects standard and best practices from above set to interact with a database.

  • Make a connection with database: Configurable, using implementation of EntityManager through a container provider
  • Transform middle tier objects: Use annotations
  • Manage session with database: Use application server support or container provider support to transaction management

If I want to draw a simple picture of this, this is how it will be

 JPA Architecture

Let us take each term to understand significance of it and requirements of it.

Entity:

  • Non final class representing DB table(s)
  • Annotated with javax.persistence.Entity
  • Either attributes or getter/setter methods with public/protected scope
  • Implements Serializable interface if to be transported across JVMs (remotly)
  • Has public/protected no argument constructor
  • Uses supported data types for attributes
  • Defines primary key using a property annotated by javax.persistence.Id, or composite key using a class
  • Abstract class can be declared as an entity
  • Super classes can be annotated as a MappedSuperClass when those are not having decoration Entity

EntityManager:

  • Implementation of javax.persistence.EntityManager
  • Manages connection with database
  • Manages persistence and retrieval of entities from database
  • Injected using javax.persistence.PersistenceContext annotation
  • Can be container-managed or application-managed
  • Supports query execution

Persistence Unit:

  • Includes all instances of entities that are managed by all EntityManagers in application
  • persistence.xml defined in META-INF directory of ear/jar defines one or more persistence units

Multiplicity in Entity Relationships:

  • One to one: Each entity instance is related to one instance of other entity. This relations is annotated using javax.persistence.OneToOne annotation.
  • One to many: One instance of an entity can be related to many instances of other entity. This relation is annotated using javax.persistence.OneToMany.
  • Many to one: Multiple instances of one entity can be related to one instance of other entity. This relation is annotated using javax.persistence.ManyToOne.
  • Many to Many: Entity instances of one entity can be related to many instances of other entity. This relation is annotated using javax.persistence.ManyToMany.

Directional Relationship:

  • Unidirectional: In this relation only one entity has field/property that refers to other entity.
  • Bidirectional: In this relation both the entities contain field/property that refers to other entity. Thus the owner entity also contains foreign key reference to the other entity.

Cascade Deletes:

Cascade is important in case of propagation of delete operation in relations. Specifying cascade=REMOVE would be required in case of OneToOne and OneToMany relations.

 

Mapping Strategies:

When we have inheritance amongst the entity classes, i.e. the root class of hierarchy is decorated with javax.persistence.Inheritance annotation, then there are three mapping strategies. The strategy applicable is defined using javax.persistence.InheritenceType enumeration. The possible values are SINGLE_TABLE, JOINED, TABLE_PER_CLASS. The default strategy is SINGLE_TABLE.

  • A single table per hierarchy: All classes in the inheritance hierarchy are persisted in single database table. The data is differentiated using discriminator type (column).
  • Table per concrete class: In this strategy there is table per concrete class. Means there is table for the parent class as well as all child classes. In this approach, the data gets duplicated.
  • Joined sub class: In this strategy there is a table which holds data from the parent class, and each sub class has a separate table. There is foreign key in each of the sub table.

 

Spring MVC Tutorial: Concepts and Code Examples

What is Spring MVC framework?

Spring MVC  framework  is

  • Spring: Using dependency injection principle
  • MVC: using model-view-controller design principle
  • Framework that provides both building blocks to build applications and few ready components

This framework provides architecture and ready components that can be used to develop presentation tier of an application. It is a light weight framework trying to overcome many limitations of other web tier frameworks like Struts and Webwork. This framework supports request and response communication through HTTP requests. Important aspects of this framework are discussed below.

Architecture:

This framework implements many JEE patterns in addition to well known MVC pattern. Front Controller, Application Controller, Intercepting Filter, View Helper, Composite View etc. patterns can be seen working in Spring MVC architecture. DispatcherServlet is the core component of Spring MVC framework. Dispatcher Servlet receives request from a client and takes it through next steps and Spring framework features. This diagram will give you a broader view of this architecture.

Spring MVC Architecture

The Dispatcher Servlet:

This is the servlet in a Spring MVC application defined in web.xml using <servlet> element. It is integrated with rest of the beans and Spring container through the configuration xml named as <servlet-name>-servlet.xml. DispatcherServlet receives all requests from clients, executes the common part of it, delegates specific implementation to the controllers, receives response in ModelandView form, i.e. data and view format, gets view ready to render, and sends response back. This is responsible for reading all configuration and using the ready components of this framework.

Controllers:

DispatcherServlet delegates the request to the controllers to execute the functionality specific part of it. There are many abstract controllers available in this framework which support specific tasks. Each abstract controller provides a method to be overridden by the controllers.

  • AbstractController: responsible for providing services applicable to any kind of HTTP request. Configurable attributes available are supportedMethods – GET/POST, requireSession, synchronizeOnSession, cacheSession, useExpiresHeader, useCacheHeader. Override handleRequestInternal(HttpServletRequest, HttpServletResponse) method.
  • ParameterizableViewController: Specifies view name to return WebApplicationContext.
  • UrlFilenameViewController: Inspects URL, retrieves file name of the file request and uses that as a view name.
  • MultiActionController: Handles multiple requests and needs MethodNameResolver or ParameterMethodNameResolver to work with. One method represents one action in this controller.
  • AbstractCommandController: Populates command object with request parameters available in controller. Offers validation features but does not offer form functionality.
  • AbstractFormController: Models forms using command objects, validates command object, and makes those available in controller. Just that id does not support the view determination.
  • SimpleFormController: It does everything that the AbstractFormController does and in addition to that it supports the view identification and redirection.
  • AbstractWizardController: As name suggests, it is to be used for Wizard kind of screen group, features required in a wizard functionality (validate, process start, process finish, etc.) are supported by this controller.

Command Objects:

These are POJOs used to bind the request data and make it available on screen. In Struts action forms, we used to extend the objects from a Struts class, but here we don’t need to do it. This is one of the advantages of Spring, that the data objects are not coupled with the framework. There is difference between the command object and form when these terms are used in Spring MVC documentation. Command object represents a POJO that can be bound with the request data, to get it populated. The term ‘Form’ is used to describe the process of binding attributes of the object with fields of a screen form. Thus, submission, resubmission etc. features are associated with respect to a form.

Handling Requests:

When a request comes to the DispatcherServlet, you may want to take it through different stages. In this framework, you can configure handlers to do this. There are many handlers available that can be used by providing handler mappings. Since you want to take the request through different process steps, the handler must be able to process the request for a definite task and forward the request to next handler in chain. For this it must also contain the list of handlers applied to this request.

  • BeanNameUrlHandlerMapping: Extends from AbstractHandlerMapping. Maps incoming HTTP request to the bean names configured in application context i.e. as a bean name, in application context, we give url and the bean is of a controller. Thus the url is mapped to a controller.

<bean name=”/saveCustomer.htm”   class=”com.myorg.springmvctutorial.web.controller.SaveCustomerController”/>

  • SimpleUrlHandlerMapping: Extends from AbstractHandlerMapping. More powerful and supports Ant-style url mapping. This mapping we configure at two places. In web.xml we define the url pattern supported.

<servlet-mapping>

<servlet-name>springmvctutorial</servlet-name>

<url-pattern>*.html</url-pattern>

</servlet-mapping>

In application context xml, we map the urls to controller definitions.

<bean class=”org.springframework.web.servlet.handler.SimpleUrlHandlerMapping”>

<property name=”mappings”>

<value>

/*/saveCutomer.htm= saveCustomerController

</value>

</property>

</bean>

  • HandlerIntercepter: Implementer of this intercept can implement three methods of this intercepter, one that is called before the actual handler execution, second after the handler execution and last one after the complete request processing. Handlers can be configured using SimpleUrlHandlerMapping configuration in application context.

View Resolving:

After completion of request processing by a controller, we need to redirect it to a view. Controller gives a view name and DispatcherServlet maps the view name to an appropriate view based on the configuration provided and redirects/forwards the request to that view. Spring MVC provides following types of view resolvers. We can have multiple view resolvers chained in the configuration files.

  • AbstractCachingViewResolver: Extending this resolver provides ability to cache the views before actually calling the views.
  • XMLViewResolver: Takes view configuration in xml format compliant with DTD of Spring’s bean factory. Default configuration is searched in WEB-INF/views.xml.
  • ResourceBundleViewResolver: Definitions are searched in resource bundle i.e. property files. Default classpath property file is searched with name views.properties.
  • UrlBasedViewResolver: Straightforward url symbol mapping to view.
  • InternalResourceViewResolver: Subclass of UrlBasedViewResolver that supports JSTL and Tiles view resolving.
  • VelocityViewReolver: Subclass of UrlBasedViewResolver used to resolve velocity views.
  • FreeMarkerViewResolver: Subclass of UrlBasedViewResolver used to resolve FreeMarker views.

Redirect and Forward

Redirecting can be achieved either by controller returning an instance of RedirectView class of Spring, or by prefixing the return view name by ‘redirect:’. If we prefix by ‘forward:’ then the response will be forwarded.

Internationalization:

This is useful for multilingual support. DispatcherServlet calls RequestContext.getLocale() method and retrieves the locale. We can add interceptors and locale resolvers to do this. There are few locale resolvers available in Spring MVC, we can tell from where the locale is retrieved by looking at their name – AcceptHeaderLocaleResolver, CookieLocaleResolver, SessionLocaleResolver. LocaleChangeInterceptor can be configured to trap the locale change. It can be used to set the view language based on the locale.

Theme Based Presentation:

Theme is used in many blogging tools to change the look and feel to give better user experience. This concept is now available in Spring MVC. Static files (e.g. css) and images constitute a theme. We can define a theme using ResourceBundleThemeSource and use theme resolvers from FixedThemeResolver, SessionThemeResolver, and CookieThemeResolver to apply the selected theme.

Multipart Support:

Spring MVC has org.springframework.web.multipart package to support multipart i.e. file upload requests. MultipartResolver implementations can be used to resolve these requests.

Exception Handling:

This framework allows you to map exceptions to views. Implementations of HandlerExceptionResolver, e.g. SimpleMappingExceptionResolver can be used to map and Exception with a error page.

Code Examples:

Following articles will take you through the detail code examples of important Spring MVC concepts.

Basic Example

Command Object

Integration with Tiles

Validation

Spring MVC Validations Example

springMost of the presentation tier frameworks provide support to client side validations. Spring MVC is not different in this principle. Just that the way it is implemented is little different. You must have gone through the painful Javascript based client side validation already, and must be in the search of a better way of doing the validations. Then Spring MVC’s solution is the right and a quick way. The best thing about this validation framework is that, it is easy to learn as well as implement. I mean you don’t need to do too many things to get it working. These are the steps to get the validation working.

Spring MVC Integrated With Tiles on Eclipse and Tomcat

Spring MVC allows integration with many technologies. If you remember Sturts with Tiles, then a similar feature is provided by Spring MVC. There is minor variation in the way it is implemented.

Hibernate, Spring, Oracle and JUnit Integration on Eclipse

Spring is mainly used to introduce loose coupling amongst different layers of application. Spring framework has enough features to provide a complete container for your application.

Internet? No, It is Google World!!!

Today, I just realized I hadn’t heard of any acquisition news from Google for the past few months. So I set out Googling for some Google news. My expedition led me to wiki page showing around 53 acquisitions of Google since 2001. Hmm, interesting stuff to read. It also gives information about the usage of that acquisition product. Google hasn’t acquired any company to do its product development, instead it has acquired products that can fit in it’s business portfolio. Trivial, isn’t it? You purchase those things that suite your current and future needs, be it an individual need or a business need. If you look at the application suite offered by Google, can you guess what Google is trying to do?
While searching for the acquisitions, I also came across pages saying ‘Google taking over the world’ and what not. I decided to investigate. In all its acquisitions, I see a peculiar taste of Google. Google’s taste is that of people, a huge people base, what you call as user base. Now go back to each application Google has offered, either by developing or through take over. Each application has a huge user base of its own and combined offers new horizons to google’s existing user base. But what kind of user base is this? I found that Google’s user base comprises predominantly of those people who want to communicate with others or get information from others on internet through self service. Yes, it is self service; these users are using the applications, and their own intellect, to get their jobs done. Google is just acting as a service provider for this purpose. It is providing them the infrastructure required for communication, or information retrieval. Let’s take an example of Google Search, specialized search, Orkut, Gmail, YouTube, Bloggers, and now the Chrome browser. Even the users of mobile technology are now included. Everywhere the user base is huge and they are using Google service to get their jobs done.
But how would that help google’s business? Google’s not here for social service. Ah! Of course through advertising!! The revenue may be a tiny amount per user, but when you have entire world as your user base, then just imagine the multiplication factor and amount of revenue.
Now can we guess what would be next shopping item of Google, which will integrate large number of new users with this Google user’s existing family, to whom Google can present the ads or other products and generate revenue? Think! think!!
Just take a look at the very familiar screen below

 

Google Applications

Now if you look at the number of acquisitions in the past one year and compare those with previous years, it is clearly visible that the count has gone down. Does that mean, Google is not able to find such products that are attracting huge number of people? Is it recession that is hitting such moves? Or has Google stopped launching products that are developed in its Google labs? You tell me!
I am sure you and me are part of this group already. So Happy searching, photo sharing, video sharing, blogging, and now even browsing!!! don’t forget to leave in your answers!

Spring MVC Tutorial With Command Object on Eclipse and Tomcat

This article is continuation of the Spring MVC Tutorial with Eclipse and Tomcat. Now, let us add the next practical aspect to our code – form or what Spring MVC calls it – command object.

Yavateshwar – A Unique Shiva Temple in Satara

Yavateshwar, another peaceful place in the outskirts of Satara city where people of Satara and around can be found spending time. Most of the visitors are of two categories. The first one, preferring to take a walk up to the temple from Bogda (tunnel) or second are those,

Post Redirect Get Design Pattern

Post redirect get design pattern solves the problem of duplicate form/data submission in a POST request (assuming you know what the difference between a POST and GET request is).

Single Threaded To Multi Threaded – A Lot to Consider

You have a batch job running in production for ages, and it was doing good job so far. But you see the business growth and anticipate that this program might become a bottleneck to the throughput.

Powered by WordPress | Designed by: seo service | Thanks to seo company, web designers and internet marketing company