Monday, April 19, 2010

Sample Code: Handling Value Change Events in JSF

There are two type of events that are generated by JSF components
• Value Change Events
• Action Events
One way to handle the events is to implement the appropriate listener. For handling action events javax.faces.event.ActionListener must be implemented and for handling value-changed events javax.faces.event.ValueChangedListener must be implemented. It must also be noted that action events are generated by controls that implement the ActionSource interface where as value-change events are generated by those controls that implement the EditableValueHolder interface.
Following is a class that implements ValueChangedListener. As can be seen that when implementing this listenen the processValueChange method must be implemented

package stu;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;

@ManagedBean(name="questionsController")
@SessionScoped
public class QuestionsController implements ValueChangeListener{
private String data;

public String getData() {
return data;
}

public void setData(String data) {
this.data = data;
}
public void processValueChange(ValueChangeEvent event) throws AbortProcessingException {
data = event.getNewValue().toString();
}
public QuestionsController() {

}

}
Registering a Listener with EditableValueHolder can be done either by specifying the type i.e. fully qualified name of class that implements ValueChangeListener (using the type attribue), or by registering an instance of ValueChangeListener implementation with the component (using binding attribute). This information is provided within the valueChangeListener tag nested inside the components tag with which the listener is to be registered.

<h:body>
<h:form>
Hello from Facelets
<h:selectOneRadio>
<f:selectItem itemValue="a" itemLabel="a"></f:selectItem>
<f:selectItem itemValue="b" itemLabel="b"></f:selectItem>
<f:valueChangeListener binding="#{questionsController}"></f:valueChangeListener>
</h:selectOneRadio>
<h:commandButton value="error" action="error"></h:commandButton>
</h:form>
</h:body>

As can be seen that error page displays the output, the code for which is given below

<h:body>
Invalid Login
<h:outputLabel value="#{questionsController.data}"></h:outputLabel>
</h:body>

Saturday, April 17, 2010

Introduction to Java Hibernate

Introduction to Java Hibernate

Objectives of this document is to give readers an understanding of the following issues

Object Relational Impedance Mismatch
Benefits of Hibernate as ORM Framework
Architecture of Hibernate Framework
Persistence Life Cycle

Object Relational Impedance Mismatch:
There are a number of differences in the Relational Model (used in database) and Object Oriented Model (used by programming languages). These differences are referred to as Impedance Mismatch. Some areas of Impedance Mismatch are as follows

Identity

In OOP “Identical” and “Equal” are different notions. Two objects are equal if they refer to the same memory location i.e. equality in OOP does not take into consideration the contents of the object but only the reference. However the “equals” method can be overridden to check the contents rather than the reference. In relational database, the equality is based upon the primary key of entity

Inheritance
In RDBMS, inheritance is not supported.
Associations
In RDBMS many-to-many relationships are not directly supported and are modeled via bridge tables. Where as in OOP such relationships can be easily modeled by having collections containing related objects at each end of the relationship. For example a student class may consist of collection having related course and course class may consist of a collection containing students related to that particular course.
Due to above reasons a number of ORM frameworks are available. However among all those, hibernate has become very popular because of the following reasons

Benefits of Hibernate


Simple and Flexible

Single configuration file and one mapping for each application object to be persisted
No need to inherit any classes

Completeness
Complete support for OOP
Has special query language similar to SQL

Performance
Issues statements only when state of object changes
Collections are loaded when they are needed
Properties are populated when needed
Users can disable which associated object will not be loaded
Supports caching

Architecture of Hibernate
Makes use of existing Java APIs including
JDBC for data access
JTA and JNDI enable integrity with JEE
Interfaces provided by Hibernate belong to four categories
Called by applications to perform CRUD and Queries e.g. Session, Transaction and Query
Called by applications to Configure hibernate, e.g. Configuration
Used by applications to react to events occurring inside hibernate. e.g. Interceptor, Lifecycle and Validatable.
Enable extending Hibernate’s powerful mapping functions e.g UserType, CompositeUserType and IdentifierGenerator. (These are implemented by application infrastructure code.)

Following is a description of some important interfaces
Session Interface
It is the Primary interface used by applications
Session is Lightweight and inexpensive to create and destroy
It must be noted that it is not thread safe
It can be considered as cache or collection of loaded objects related to a single unit of work
Also called persistence manager as it performs loading and saving

SessionFactory

Instances of SessionFactory are Heavy weight
And thread safe as they are Intended to be shared among multiple threads
Each object of sessionFactory will represent a single database
Caches generated SQL, mapping metadata for runtime and data (only in-case of second-level cache)

Configuration interface
The Configuration object is used to configure and bootstrap Hibernate
Creates the SessionFactory

Transaction

Optional Interface
Abstracts application code from underlying transaction implementation

Query and Criteria Interface
Query is lightweight and can’t be used out of session
can be used to
Bind parameters
Limit the number of result
Execute Query

Criteria is similar to queries
Create and execute object oriented criteria queries

Callback Interfaces
Allows applications to receive notifications
LifeCycle and Validate needs to be implemented by persisted classes(Not preferred)
Interceptor needs not be implemented by persistent classes.

Type interface
Hibernate supports rich type system
Nevertheless, custom types can be created using
UserType
CompositeUserType

Extension Interfaces
Customized Implementation of certain interfaces possible
Enables plugging in code into hibernate framework
Extension Points and Corresponding Interfaces
Primary key generation (IdentifierGenerator interface)
SQL dialect support (Dialect abstract class)
Caching strategies (Cache and CacheProvider interfaces)
DBC connection management (ConnectionProvider interface)
Transaction management (TransactionFactory, Transaction, and TransactionManagerLookup interfaces)
ORM strategies (ClassPersister interface hierarchy)
Property access strategies (PropertyAccessor interface)
Proxy creation (ProxyFactory interface)

Persistence Life Cycle
Hibernate persistence is Transaction-Scoped
In the context a row will be represented by a single instance
When same row is retrieved twice reference to single instance will be returned
Defines three states for an object
Transient
Persistent
Detached

Transient
Objects created with new operator
Not associated with any database row
Their state garbage collected when dereferenced
Considered non-transactional by hibernate
Can be made persistent
By calling save method
Creation of reference from an already persistent instance

Persistent
Any instance with a database identity
Always associated with persistence manager i.e. Session
Are Transactional
i.e. Their state is synchronized with database at the end of transaction
SQL queries are used for this purpose
Can be retrieved from database by
Executing Query
Identifier Lookup
Navigating object graph starting from persistent instance
Instance is called new if Identity allotted but not stored in database yet

Detached
Objects no longer associated with persistence manager
This happens when the session is closed
Their state is no longer guaranteed to be synchronized with Database
A detached instance can be re-associated with another Persistence manager

Above were some of the basics of Hibernate. This post will be appended with more material related to hibernate basics.

Thursday, April 15, 2010

Writing SQL Query

This material guides how to make the right query inorder to retrieve particular records. It has been observed that often students are not sure that what can be applied to retrieve the required records

This article will use the following schema

order(orderid, orderdate, customerid)
customer(cutomerid, customername)

1- Whenever an objective is given first determine the resources/tables that are required. This can be done either by looking at the columns that are required to be displayed or the columns on the basis of which filteration of rows is done.

for example given the following objective
Find the dates of all orders

The above objective asks for the date of all orders which clearly indicates that orderdate column is required which is present in the order table. Thus the query will be

Select orderDate from orders

However if the objective is to display the orderDates as well as customerNames then the query will be modified. Here the objective indicates that orderDate is required which is in the order table and customerName is required which is in the customer table. Thus the query will need to join the contents of two tables which is always on the basis of common column. The query in this case will be

Select customerName, orderDate from order, customer where order.orderno=customer.custno

2- Secondly determine whether all records need to be displayed or some filteration needs to be applied. For example, if the objective is to display the orderdate and name of customer who have placed order on '10/10/2010' then we need to appy filteration on the basis of orderdate. This is in addition to join-condition which is there due to the reason that orderDate and customerName are in different table. The query in this case will be

Select customerName, orderDate from order, customer where order.orderno=customer.custno and orderDate='10/10/2010'

3- Thirdly, see if there is a need of aggregates or summarized columns. If the query asks for a single aggregate then use appropriate aggregate function, however, if it requires multiple aggregates based upon values of particular column then apply group by. For example if the objective is to determine total number of orders then the query will be

Select count(*) from orders

Do note that the objective was to calculate a single aggregate for the entire table therefore group by has not been applied. In addition, since the resources required for the query were present in one table therefore no join was applied and finally there was no need of filteration as a single total for entire table was required. However if the objective is modified such that only total number of orders placed on '10/10/2010' is required then a where clause will be appended in the above query as filteration is now needed

Select count(*) from orders where orderDate='10/10/2010'

As mentioned that in cases where a number of summaries are needed to be displayed then a group by clause is appended. For example if we need to display summaries on the basis of customer, i.e. total number of orders placed by each customer then group by clause containing name of customer related column will be appended

Select count(*) from orders group by customerId

4- The final step is to see whether all summaries (outputs of aggregates) need to be displayed or only particular ones. For example if the above objective is modified such that only those customerids are required to be displayed that have more than 5 orders, then we need to apply the having clause.

Select count(*) from orders group by customerId having count(*)> 5

To summarize, having is applied when output of group by needs to be filtered

Please note that the list is not exhaustive and some more points may be added in future. However for most of the scenarios the above point will be a very great help