Saturday, August 11, 2012

Method Overriding in Java

public class First {

public void abc ()
{
System.out.println("First");
}

public void xyz ()
{
System.out.println("First_XYZ");
}
}

------------------------------------------------------------------------------------------

public class Second extends First {
public void abc ()
{
System.out.println("Second");
}

public static void main(String args[])
{
First first = new First();
first.abc();//First

Second sec = new Second();
sec.abc();//Second

First cc = new Second();
cc.abc();//Second

Object a = new Second();
System.out.println(a.getClass());//class Second

First fs = (First) new Second();
fs.abc();//Second



/************************************/
First c = new Second();
c.xyz();//First_XYZ as there is no xyz() method in this class

First f = (First) new Second();
f.xyz();//First_XYZ as there is no xyz() method in this class

/************************************/
Second dd = (Second) new First();
dd.abc();//java.lang.ClassCastException: First cannot be cast to Second

}
}



------------------------------------------------------------------------------------------
First
Second
Second
class Second
Second
First_XYZ
First_XYZ
java.lang.ClassCastException: First cannot be cast to Second
at Second.main(Second.java:34)


Wednesday, August 8, 2012

GenericServlet vs HttpServlet



GenericServlet
HttpServlet
Belongs to javax.servlet package
Belongs to javax.servlet.http package
GenericServlet is an ABSTRACT CLASS 

Extends
  • Object

Implements
  • Servlet
  • ServletConfig
  • java.io.Serializable


HttpServlet is an ABSTRACT CLASS

Extends
  • GenericServlet

Implements
  • java.io.Serializable


To write a GenericServlet you need abstract service() to be overridden
A subclass of HttpServlet must override at least one method of
  • doGet()
  • doPost()
  • doPut()
  • doDelete()
  • init()
  • destroy()
  • getServletInfo()


JDBC vs Hibernate



JDBC 
Hibernate 
With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.  
Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this. 
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.  
Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.  
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.  
Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.  
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. 
Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.  
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.  
Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.  
With JDBC, caching is maintained by hand-coding.  
Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.  
In JDBC there is no check that always every user has updated data. This check has to be added by the developer.  
Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.  
JDBC Architecture
JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to
access database:

  1. Open connection to database,
  2. Use JDBC driver to send SQL queries to database,
  3. Process the results that are returned, and
  4. Close the connection.
JDBC uses two architectures to communicate with database:
1) The driver connects to database and executes SQL statements. Results are sent back from
driver to driver manager and finally to the application.
2) The JDBC driver communicates with ODBC driver. ODBC driver executes SQL query and
then results are sent back to JDBC driver to driver manager and then to application
Hibernate Architecture
1) itself opens connection to database, 
2) converts HQL (Hibernate Query Language) statements to database specific statement, 
3) receives result set,
4) then performs mapping of these database specific data to Java objects which are directly used
by Java application. 
Hibernate uses the database specification from Hibernate Properties file. Automatic mapping is
performed on the basis of the properties defined in hbm XML file defined for particular Java object. 


Tuesday, August 7, 2012

BeanFactory vs ApplicationContext





ApplicationContext is much the same as a BeanFactory. 

Both 
  • load bean definitions
  • wire beans together
  • dispense beans upon request.

The ApplicationContext includes all functionality of the BeanFactory, it is generally recommended over the BeanFactory.
BeanFactory can still be used for light weight applications like mobile devices or applet based applications.

BeanFactory

ApplicationContext

·         An Interface that implements Factory-Pattern
·         A bean factory “lazily loads” all beans, deferring bean creation until the getBean() method is called.

·         Extends BeanFactory
·         An application context PRELOADS all singleton beans upon context startup. By preloading singleton beans, you ensure that they will be ready to use when needed—your application won’t have to wait for them to be created.
·         Application contexts provide a means for resolving text messages, including support for internationalization (I18N) of those messages.
·         Application contexts provide a generic way to load file resources, such as images.
·         Application contexts can publish events to beans that are registered as listeners.

XmlBeanFactory: A simple BeanFactory that loads a context definition file by way of a java.io.InputStream.
ClassPathXmlApplicationContext: it loads a context definition from an XML file located in the class path, treating context definition files as class path resources.
 e.g. ApplicationContext context = new ClassPathXmlApplicationContext(“foo.xml”);

FileSystemXmlApplicationContext: It loads a context definition from an XML file in the filesystem.
e.g ApplicationContext context = new FileSystemXmlApplicationContext(“c:/foo.xml”);

XmlWebApplicationContext: It loads context definitions from an XML file contained within a web application.


Monday, August 6, 2012

instanceof v/s isInstance

instanceof
isInstance()
reserved word
method of java.lang.Class.
Could use instanceof on types (which are known on compile time)
 isInstance() could only be called on an instance for java.lang.Class.
if (obj instanceof MyType) {
...
}


if (MyType.class.isInstance(obj)) {
...
}

so you can have dynamism using isInstane() like this:



   Class x = Integer.class;

   if (x.isInstance(obj)) {
   ...
   }

   x = String.class;

   if (x.isInstance(obj)) {
   ...
   }


as you see you could check the type of an object with an unknown class during compile time!
instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception.
isInstance() Determines if the specified Object is assignment-compatible with the object represented by this Class.

Saturday, August 4, 2012

Data access object





A data access object (DAO) is an object that provides an abstract interface to some type of database or persistence mechanism, providing some specific operations without exposing details of the database. It provides a mapping from application calls to the persistence layer. This isolation separates the concerns of what data accesses the application needs, in terms of domain-specific objects and data types (the public interface of the DAO), and how these needs can be satisfied with a specific DBMS, database schema, etc. (the implementation of the DAO).
This design pattern is equally applicable to most programming languages, most types of software with persistence needs and most types of databases, but it is traditionally associated with Java EE applications and with relational databases accessed via the JDBC API because of its origin in Sun Microsystems' best practice guidelines[1] ("Core J2EE Patterns") for that platform.

The advantage of using data access objects is the relatively simple and rigorous separation between two important parts of an application that can and should know almost nothing of each other, and which can be expected to evolve frequently and independently. Changing business logic can rely on the same DAO interface, while changes to persistence logic do not affect DAO clients as long as the interface remains correctly implemented.
§  Can be used in a large percentage of applications - anywhere data storage is required.
§  Hide all details of data storage from the rest of the application.
§  Act as an intermediary between the application and the database. They move data back and forth between objects and database records.
§  Allow ripple effects from possible changes to the persistence mechanism to be confined to a specific area
§  Appication is independent of the data access techniques and database dependency.
§  Offers loose coupling with the other layers of application
§  Allows to unit test the service layer using mock objects without connecting to database



Data Access templates in spring





  •          JmsTemplate class.
  •          JdbcTemplate class.
  •         SimpleJdbcTemplate class.
  •          NamedParameterJdbcTemplate class.
  •          SqlMapClientTemplate class.
  •          HibernateTemplate class.
  •          JdoTemplate class.
  •          JpaTemplate class.


·         JmsTemplate class (org.springframework.jms.core.JmsTemplate)
It is a general-purpose class for managing Java Messaging Service (JMS) connections. One of the main advantages of this class is that it simplifies the JMS synchronous access codes.



           JdbcTemplate class (org.springframework.jdbc.core.JdbcTemplate)
It is a wrapper around a JDBC data source, enabling you to access a JDBC database using SQL operations.

  1. It simplifies the use of JDBC since it handles the creation and release of resources                      This helps to avoid common errors such as forgetting to always close the connection.
  2. It executes the core JDBC workflow like statement creation and execution, leaving application code to provide SQL and extract results                                                       This class executes SQL queries, update statements or stored procedure calls, imitating iteration over ResultSets and extraction of returned parameter values.
  3. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package.


examples


 this.jdbcTemplate.queryForInt
 this.jdbcTemplate.queryForObject
 this.jdbcTemplate.query
 this.jdbcTemplate.update("insert/delete/update

·         SimpleJdbcTemplate class (org.springframework.jdbc.core.simple.SimpleJdbcTemplate)
It is a convenience wrapper around the JdbcTemplate class. This class has been tear down so that it includes only the most commonly used template methods and it has been optimized to exploit Java 5 features.

·         NamedParameterJdbcTemplate class (org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate)
It is a convenience wrapper around the JdbcTemplate class, which enables you to use named parameters instead of the usual ? placeholders embedded in a SQL statement.

·         SqlMapClientTemplate class (org.springframework.orm.ibatis.SqlMapClientTemplate)
It is a simplifying wrapper around the iBATIS SqlMapClient class. iBATIS is an Object Relational Mapper (ORM) that is capable of automatically instantiating Java objects based on a given SQL database schema.

·         HibernateTemplate class (org.springframework.orm.hibernate3.HibernateTemplate)
It provides an alternative to working with the raw Hibernate 3 session API (based on sessions returned from SessionFactory.getCurrentSession()).

·         JdoTemplate class (org.springframework.orm.jdo.JdoTemplate)
It provides an alternative to working with the raw JDO PersistenceManager API. The main difference between the APIs relates to their exception handling. See the Spring JavaDoc for details.

·         JpaTemplate class (org.springframework.orm.jpa.JpaTemplate)
It provides an alternative to working with the raw JPA EntityManager API..