Tuesday, December 31, 2013

JDBC Connectivity

You can not do everything in RAM. You need persistence.


Persistence can be achieved by writing to files or using Serilization too but Database is a more flexible way. Some of my friends are searching a way to connect to DB. This post is dedicated to them.

 I am assuming that the DB is Oracle. Following is a program to connect to a DB. Unfortunately I don't have a DB installed. So could not test it either but this will run accordingly with your DB.

1. Get the driver from http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html
2. Add this jar to your program classpath
3. Get the database parameters such as, database host, database port, database service name, database user name, database password
4. Edit the following program with required details as I mentioned in point 2


 import java.io.IOException;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.PreparedStatement;  
 import java.sql.ResultSet;  
 import java.sql.SQLException;  
 /**  
  *   
  */  
 /**  
  * @author Palash  
  *   
  */  
 public class MySecondProgram {  
      /**  
       * @param args  
       * @throws ClassNotFoundException  
       * @throws SQLException  
       * @throws IOException  
       */  
      public static void main(String[] args) throws ClassNotFoundException,  
                SQLException {  
           // Loads the driver and register it.  
           Class.forName("oracle.jdbc.driver.OracleDriver");  
           // Gets the connection  
           Connection conn = DriverManager.getConnection(  
                     "jdbc:oracle:thin:@DB_HOST:DB_PORT:DB_SERVICE_NAME",  
                     "USER_NAME", "PASSWORD");  
           // Prepare a statement to run on the connection  
           PreparedStatement statement = conn  
                     .prepareStatement("SELECT 'a' FROM DUAL");  
           // Run the qury in DB and get results  
           ResultSet rs = statement.executeQuery();  
           // Now, extract data from result set  
           while (rs.next()) {  
                String data = rs.getString(0);  
                System.out.println(data);  
           }  
      }  
 }  

5. Compile and run it.

Hope this helps you out.
Don't just stop here, if this article helped you out, spread the word.
Next
Palash Kanti Kundu

Monday, December 30, 2013

JDBC Drivers...

After the article on JDBC connectivity, I thought of providing my readers with the drivers required for some commonly used database. Which also can serve the purpose of a quick reference.
So, no more descriptions on it, let's get to the point.

Following are the databases Java connects with their Drivers,

DatabaseTested
Versions
JDBC DriverDatabase Specific
Support
Supported
Features
DB2 LUW8.2+, 9.7, 10.xInfoRead MoreList
H21.3, 1.4InfoRead MoreList
Informix9, 10, 11, 12InfoRead MoreList
JavaDB/Derby10InfoRead MoreList
Microsoft SQL Server2000-2014InfoRead MoreList
Mimer SQL9.1, 9.2, 9.3, 10InfoRead MoreList
MySQL3.23, 4, 5InfoRead MoreList
NuoDB2.0.4InfoRead MoreList
Oracle8i, 9i, 10g, 11g, 12cInfoRead MoreList
PostgreSQL8, 9InfoRead MoreList
SQLite3.6, 3.8.6InfoRead MoreList
Sybase ASE12.5, 15InfoRead MoreList
Vertica6.1.3, 7.0, 7.1InfoRead MoreLis

Hope this quick reference help you...
Don't just stop here, if this article helped you out, spread the word.

Palash Kanti Kundu

Monday, December 2, 2013

Introduction to Object Relational mapping...

We hear about Objects, we hear about relational databases. What is ORM then ?

We use relational databases as a backbone of our middle tier applications written in Object Oriented Programming Languages. In most of the scenarios we manipulate over data through our applications. To design the functionality of the application we generally use high level languages such as C++, Java, VB.net, C# etc. Now, to deal with relational database in back-end we need specific language which are based on relational tables, widely known as SQL (Structured Query Language).

Like java applications understand only objects, databases understand only tables and relations between them.

Hey wait, I have a question here, if they can talk different languages, how do they exchange information ?
Yes you are right, there is a gap between these two. To address this gap between  object oriented and relational model in traditional way we used JDBC. Java to Database Connectivity can be successfully achieved through JDBC but JDBC returns data in form of  resultset which have certain limitations like it will be more complex for large projects where we have multiple database tables and multiple objects to synchronize. Always programatically developer has to change relational data to java objects. Same functionality we can achieve in an effective way through ORM. Object relational mapping is the technique to convert data between relational data and object oriented data.
Now, we can go for a formal definition of ORM,
ORM - ORM is a technique to convert Objects into Database relations and vice-versa. That's it. Following is a visual representation for t he same,
ORM technique


Hmmm...(Awww...), it makes things simpler. Interesting. So, how do we do it ?
In the world of Java, Object relational mapping can be achieved through many tools such as Hibernate, Java Data Objects (JDO),Spring ORM and many more.
These tools are highly configurable, thus they are highly maintainable, reusable and really makes life easy while working with data.

So, which tool is the best ?
Well, every one has its own pros and cons. All come in different features and functionality. Each has their own implementations and . I will be talking about Hibernate here. So, you are free to chose anyone based on your application requirement.

Now, I have an example on how Hibernate helps in achieving this feature,

Lets say you are an Odia guy and you want some books from your friend who is a Bengali guy i.e your friend has Bengali version of the books you want. So to read those books you can do two things either you yourself convert the books in to Odia and then read else ask any translator to translate the book and provide you with the translated version of the Bengali books.
Here the first way is working as a normal JDBC flow where developer has the whole responsibility of translating the back-end data into Java objects. On the other hand, the second way is treated as Hibernate translation. Where the translator is working on translating the back-end data into Java objects and developer is more concentrated on the business logic.

Well, I would like to thank one of my readers who has contributed this article.
Article contributed by: Amrita Pattnaik

Palash Kanti Kundu

Sunday, December 1, 2013

Don't repeat the DAO !!!

Most of the time, DAO objects we create, we basically promote the same functionality for different object types.
For example, take the following two implementations.

Implementation of Person DAO for Person related operations
 /*  
  * Copyright 2014-2014 Palash Kanti Kundu.  
  *  
  * Licensed under the Apache License, Version 2.0 (the "License");  
  * you may not use this file except in compliance with the License.  
  * You may obtain a copy of the License at  
  *  
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *  
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  *   
  */  
 import java.io.Serializable;  
 import java.util.List;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.springframework.orm.hibernate4.HibernateTemplate;  
 /**  
  * Person DAO implementation with basic CRUD operations.  
  *   
  * @author Palash Kanti Kundu  
  * @version 1.0  
  */  
 public class PersonDAOImpl {  
      private HibernateTemplate hibernateTemplate;  
      private SessionFactory sessionFactory;  
      public List<Person> fetchAll() {  
           @SuppressWarnings("unchecked")  
           List<Person> objectList = (List<Person>) hibernateTemplate  
                     .find("from Person");  
           return objectList;  
      }  
      public Person fetchById(Serializable id) {  
           return hibernateTemplate.get(Person.class, id);  
      }  
      public void save(Person bean) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           session.save(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
      public void update(Person bean) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           session.update(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
      public void deleteById(Serializable id) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           Person bean = fetchById(id);  
           session.delete(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
 }  


Implementation of Employee DAO for Employee related operations
 /*  
  * Copyright 2014-2014 Palash Kanti Kundu.  
  *  
  * Licensed under the Apache License, Version 2.0 (the "License");  
  * you may not use this file except in compliance with the License.  
  * You may obtain a copy of the License at  
  *  
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *  
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  *   
  */  
 import java.io.Serializable;  
 import java.util.List;  
 import org.hibernate.Session;  
 import org.hibernate.SessionFactory;  
 import org.hibernate.Transaction;  
 import org.springframework.orm.hibernate4.HibernateTemplate;  
 /**  
  * Employee DAO implementation with basic CRUD operations.  
  *   
  * @author Palash Kanti Kundu  
  * @version 1.0  
  */  
 public class EmployeeDAOImpl {  
      private HibernateTemplate hibernateTemplate;  
      private SessionFactory sessionFactory;  
      public List<Employee> fetchAll() {  
           @SuppressWarnings("unchecked")  
           List<Employee> objectList = (List<Employee>) hibernateTemplate  
                     .find("from Employee");  
           return objectList;  
      }  
      public Employee fetchById(Serializable id) {  
           return hibernateTemplate.get(Employee.class, id);  
      }  
      public void save(Employee bean) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           session.save(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
      public void update(Employee bean) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           session.update(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
      public void deleteById(Serializable id) {  
           Session session = sessionFactory.openSession();  
           Transaction transaction = session.beginTransaction();  
           Employee bean = fetchById(id);  
           session.delete(bean);  
           session.flush();  
           transaction.commit();  
           session.close();  
      }  
 }  

So, we can see that both the classes basically achieve the same set of functionality but on different type. Now, if you go through these implementations and think it in a different way, you can find that, with Java 5.0 you can write it a single time and use it for different types with Generics.
Hibernate and Spring gives you the flexibility to use this concept in a fine grained way.

Well, it can be done in various ways, one implementation is here. You can check this article, its a great way to achieve the Generic DAO  implementation.
I have done it in another way, depending on my application needs. In my application, any persistence object is of type IBean. So, I have used the following DAO implementation in my application


 /*  
  * Copyright 2014-2014 Palash Kanti Kundu.  
  *  
  * Licensed under the Apache License, Version 2.0 (the "License");  
  * you may not use this file except in compliance with the License.  
  * You may obtain a copy of the License at  
  *  
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *  
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  *   
  */  
 package com.palash90.assistant.dao;  
 import java.io.Serializable;  
 import java.util.List;  
 import org.hibernate.Criteria;  
 import org.hibernate.SessionFactory;  
 import org.springframework.orm.hibernate4.HibernateTemplate;  
 import com.palash90.assistant.beans.IBean;  
 /**  
  * DAO interface  
  *   
  * @author Palash Kanti Kundu  
  * @version 1.0  
  */  
 public interface IDao {  
      /**  
       * Returns the list of objects of the provided class  
       *   
       * @return  
       */  
      public List<? extends IBean> fetchAll(Class<? extends IBean> cls);  
      /**  
       * Returns the object with the provided id  
       *   
       * @return  
       */  
      public <T extends IBean> T fetchById(Class<T> cls, Serializable id);  
      /**  
       * Saves the bean to database  
       *   
       * @param bean  
       */  
      public void save(IBean bean);  
      /**  
       * Updates the bean in the database  
       *   
       * @param bean  
       */  
      public void update(IBean bean);  
      /**  
       * Deletes the bean from the database  
       *   
       * @param bean  
       */  
      void deleteById(Class<? extends IBean> cls, Serializable id);  
      /**  
       * Set the sessionFactory to be used  
       */  
      void setSessionFactory(SessionFactory sessionFactory);  
      /**  
       * Set the hibernateTemplate to be used  
       */  
      void setHibernateTemplate(HibernateTemplate hibernateTemplate);  
      /**  
       * Returns the list of object of Class type for the provided criteria  
       *   
       * @param cls  
       * @param criteria  
       * @return  
       */  
      <T extends IBean> List<T> fetchByCriteria(Class<? extends IBean> cls,  
                Criteria criteria);  
 }  

And this is the implementation,

 /*  
  * Copyright 2014-2014 Palash Kanti Kundu.  
  *  
  * Licensed under the Apache License, Version 2.0 (the "License");  
  * you may not use this file except in compliance with the License.  
  * You may obtain a copy of the License at  
  *  
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *  
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  *   
  */  
 package com.palash90.assistant.dao;  
 import java.io.Serializable;  
 import java.util.List;  
 import org.hibernate.Criteria;  
 import org.hibernate.Session;  
 import org.hibernate.Transaction;  
 import com.palash90.assistant.beans.IBean;  
 import com.palash90.assistant.constants.AssistantConstants;  
 /**  
  * Generic DAO implementation with basic CRUD operations.  
  *   
  * @author Palash Kanti Kundu  
  * @version 1.0  
  */  
 public class GenericDAOImpl extends AbstractDaoImpl {  
   /*  
    * (non-Javadoc)  
    *   
    * @see com.palash90.assistant.dao.IDao#fetch(java.lang.Class)  
    */  
   @Override  
   public List<? extends IBean> fetchAll(Class<? extends IBean> cls) {  
      @SuppressWarnings("unchecked")  
      List<? extends IBean> objectList = (List<? extends IBean>) hibernateTemplate  
           .find(AssistantConstants.FROM + AssistantConstants.SPACE  
                + cls.getCanonicalName());  
      return objectList;  
   }  
   /*  
    * (non-Javadoc)  
    *   
    * @see com.palash90.assistant.dao.IDao#fetchById(java.lang.Class,  
    * java.io.Serializable)  
    */  
   @Override  
   public <T extends IBean> T fetchById(Class<T> cls, Serializable id) {  
      return hibernateTemplate.get(cls, id);  
   }  
   /*  
    * (non-Javadoc)  
    *   
    * @see com.palash90.assistant.dao.IDao#save(com.palash90.assistant  
    * .beans.IBean)  
    */  
   @Override  
   public void save(IBean bean) {  
      Session session = sessionFactory.openSession();  
      Transaction transaction = session.beginTransaction();  
      session.save(bean);  
      session.flush();  
      transaction.commit();  
      session.close();  
   }  
   /*  
    * (non-Javadoc)  
    *   
    * @see com.palash90.assistant.dao.IDao#update(com.palash90.assistant  
    * .beans.IBean)  
    */  
   @Override  
   public void update(IBean bean) {  
      Session session = sessionFactory.openSession();  
      Transaction transaction = session.beginTransaction();  
      session.update(bean);  
      session.flush();  
      transaction.commit();  
      session.close();  
   }  
   /*  
    * (non-Javadoc)  
    *   
    * @see com.palash90.assistant.dao.IDao#delete(com.palash90.assistant  
    * .beans.IBean)  
    */  
   @Override  
   public void deleteById(Class<? extends IBean> cls, Serializable id) {  
      Session session = sessionFactory.openSession();  
      Transaction transaction = session.beginTransaction();  
      IBean bean = fetchById(cls, id);  
      session.delete(bean);  
      session.flush();  
      transaction.commit();  
      session.close();  
   }  
   /*  
       * (non-Javadoc)  
       *   
       * @see dao.IDao#fetchByCriteria(java.lang.Class, org.hibernate.Criteria)  
       */  
      @SuppressWarnings("unchecked")  
      @Override  
      public <T extends IBean> List<T> fetchByCriteria(Class<? extends IBean> cls,Criteria criteria) {  
           return (List<T>) criteria.list();  
      }  
 }  

Now, if you need a specific kind of implementation for any of particular, you can inherit the generic implementation and add the particular functionality, like I have done for my Person DAO,

 /*  
  * Copyright 2014-2014 Palash Kanti Kundu.  
  *  
  * Licensed under the Apache License, Version 2.0 (the "License");  
  * you may not use this file except in compliance with the License.  
  * You may obtain a copy of the License at  
  *  
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *  
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  *   
  */  
 package com.palash90.assistant.dao;  
 import java.util.List;  
 import org.hibernate.Criteria;  
 import org.hibernate.criterion.Restrictions;  
 import com.palash90.assistant.beans.person.Person;  
 public class EmployeeDaoImpl extends GenericDAOImpl {  
      /**  
       * Returns the list of persons with the name provided  
       *   
       * @param name  
       * @return  
       */  
      public List<Person> fetchByName(String name) {  
           Criteria criteria = sessionFactory.openSession().createCriteria(  
                     Person.class);  
           criteria.add(Restrictions.eq("firstName", name));  
           return fetchByCriteria(Person.class, criteria);  
      }  
 }  

Hope that, you get some idea about implementing your DAO in a generic way.
Now, Don't repeat the DAO.

Thanks for reading !!!

Palash Kanti Kundu