Friday, October 22, 2010

Spring with in a Day Part-2

Spring DAO Module:
---------------------------------------
i. We can use JDBC, Hibernate, TopLink, JPA etc for accessing database from spring based application.
ii. Spring provides some class for different ORM technologies link JdbcTemplate, HibernateTemplate, TopLinkTemplate, JpaTemplate etc.
iii. As part of spring the class with the naming pattern xxxTemplate (JdbcTemplate, HibernateTemplate etc.) is provided. These classes simplify the development of the application that has to use the database.

Note:
* Datasource manages the set of connection pool
* Connection pool is the set of connection mint for the performance of the database connection
* Apache people provides the DataBaseConnetionPool(DBCP) to maintain database connection pool.




JDBC in Spring
---------------------------------
i. JdbcTemplate internally uses the DataSource that is responsible for maintaining the connection pool.
ii. DBCP software is provided by Apache (apache.org) is can use for configuring the connection pool.
iii. For using DBCP the following jar files are required –
=> commons-dbcp-1.2.2.jar
=> commons-pool-1.3.jar
=> commons-collections-3.2.jar



iv. The JdbcTemplate uses the DataSource object whenever database operation has to be performed the jdbcTemplate picks up the connection from ConnectionPool using the DataSource object.
v. < bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
lazy-init="default" autowire="default" dependency-check="default">
            < property name="driverClassName" value="com.mysql.jdbc.Driver" />
            < property name="url" value="jdbc:mysql://localhost:3306/testDB" />
            < property name="username" value="root" />
            < property name="password" value="root" />
< /bean>
vi. < bean id=”jtb” class=”org.springframework.jdbc.core.JdbcTemplate”>
             < properties name=”dataSource”>
                    < ref bean=”dataSource”>< /ref>
             < /properties>
     < /bean>

Example:
------------------
package pack;
public class SprApp {
      public static void main(String [] args) {
            ApplicationContext sprCont=new ClassPathXmlApplicationContext(“applicationContext.xml”);
            JdbceTemplate jt=(JdbcTemplate) sprCont.getBean(“jtb”);

            //non parameterized query
            String nonParamSqlQuery=”insert into Emp values (1,’eone’,1000)”;
            Jt.update(nonParamSqlQuery);

            // parameterized query
            String paramSqlQuery=”insert into Emp values(?,?,?)”;
            Object param[] =new Object[3];
            param[0]=”100”;
            param[1]=”EHun”;
            param[2]=”12345”;
            jt.update(paramSqlQuery,param);
      }
}

ResultSetExtractor
-----------------------------------
• ResultSetExtractor is an interface; we must implements this interface to deal with the data obtained with database.
• As part of the spring, Template design pattern is used for the design of the classes like JdbcTemplate, HibernateTemplate etc.
• A Template document is a simple document. When we want to create a new document we can fill in the blanks that are part od the template document.
• In case of template design pattern, part of the code is provided as part of the classes like JdbcTemplate and we can provide part of the code by implementing the interfaces like ResultSetExtractor (providing the classes implementing interfaces are similar to filling the blanks in the pattern template document).




Example:
-------------------------
package pack;
public class OurRsExt implements ResultSetExtractor {
      public Object extractData(ResultSet rs) throws SQLException,DataAccessException {
            while(rs.next()){
                   //set the value in object
                   System.out.println(“data=”+rs.getString(1));
            }
            return null;
     }
}
package pack;
public class SprApp {
      public static void main(String [] args) {
            ApplicationContext sprCont=new ClassPathXmlApplicationContext(“applicationContext.xml”);
            JdbceTemplate jt=(JdbcTemplate) sprCont.getBean(“jtb”);

             //select query
             String selectSqlQuery=”select * from Emp”;
             Jt.query(vsql, new OurRsExt());
       }
}

Hibernate in Spring
----------------------------------------
i. We need to use HibernateTemplate object for accessing the data using Hibernate API from the spring based application.
ii. HibernateTemplate depends upon SessionFactory that is depends upon DataSource object.



iii. < bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
lazy-init="default" autowire="default" dependency-check="default">
             < property name="driverClassName" value="com.mysql.jdbc.Driver" />
             < property name="url" value="jdbc:mysql://localhost:3306/testDB" />
             < property name="username" value="root" />
             < property name="password" value="root" />
      < /bean>
iv. < bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            < property name="dataSource">
                    < ref bean="dataSource" />
            < /property>
            < property name="configLocation">
                    < value>hibernate.cfg.xml< /value>
            < /property>

            < property name="configurationClass">
                    < value>org.hibernate.cfg.AnnotationConfiguration< /value>
            < /property>
            < property name="hibernateProperties">
                    < props>
                            < prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect < /prop>
                    < /props>
             < /property>
      < /bean>
v. < bean id="htb"class="org.springframework.orm.hibernate3.HibernateTemplate">
            < property name="sessionFactory">
                    < ref bean="sessionFactory" />
            < /property>
< /bean>

Example
---------------------
package pack;
public class SprApp {
      public static void main(String [] args) {
            ApplicationContext sprCont=new ClassPathXmlApplicationContext(“applicationContext.xml”);
            HibernateTemplate jt=(HibernateTemplate) sprCont.getBean(“htb”);
          
             //insert operation
             Employee e=new Employee();
             e.setEno(new Long(1));
             e.setEmpName(“Eone”);
             e.setSalary(new Double(12345));
             ht.save(e);

             //select or load operation
             Employee el=new Employee();
             ht.load(el,new Long(1));

             //delete operation
             Employee ed=new Employee();
             ht.load(ed,new Long(1));
             ht.delete(ed)

             //update operation
             Employee eu=new Employee();
             ht.load(eu,new Long(1));
             eu.setSalary(new Double(23456));
             ht.update(eu);

             //select or load operation without primary key
             String selectQry=”from Employee”;
              List< Employee> employeeList=ht.find(selectQry);
      }
}
vi. HibernateTemplate object.find() method can be used for executing the HQL statement. Internally Query object will be created and execute the Query object to fetch the record.

1 comment: