Docstoc

dm0604balani-pdf

Document Sample
dm0604balani-pdf Powered By Docstoc
					     Develop DB2 applications using persistence-based
     frameworks
     Skill Level: Introductory


     Naveen Balani
     Technical Architect
     Webify Solutions



     06 Apr 2006


     Get an overview of various persistence-based frameworks for IBM® DB2® Universal
     Database™ (DB2 UDB) for Linux®, UNIX®, and Windows®, including Hibernate,
     Java™ Data Objects (JDO), and Java DataBase Connectivity (JDBC™) 3.0. Build
     DB2 persistence-based applications employing the widely used Hibernate and Spring
     framework.


     Section 1. Before you start

     About this tutorial
     Take a look at the commonly used persistence frameworks like Hibernate, JDO, and
     plain JDBC 3.0 with DB2, and build a sample application that incorporates the
     declarative transaction handling of Spring AOP and the persistence backbone of
     Spring with Hibernate.


     Prerequisites
     To download and run the sample application, you must first install the software listed
     in Resources:

               • DB2 for Linux, UNIX, and Windows


Develop DB2 applications using persistence-based frameworks                              Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                                  Page 1 of 14
developerWorks®                                                               ibm.com/developerWorks




               • Spring framework




     Section 2. JDO, JDBC, and Hibernate

     Introduction to JDO
     The Java Data Objects (JDO) API is a standard interface-based Java model
     abstraction of persistence to directly store Java domain model instances into a data
     store. JDO is developed as a part of a Java Specification Request.

     With respect to application development, a programmer can write code in the Java
     programming language that transparently accesses the underlying data store,
     without using database-specific code. The features of JDO technology are:

               • Portability: Applications written with the JDO API can be run on multiple
                 implementations without recompiling or changing source code.
               • Database independence: Applications written with the JDO API are
                 independent of the underlying database.
               • Focus on domain model: Programmers can focus on their domain
                 model and leave the details of persistence to the JDO implementation.
               • High performance: Programmers can delegate the details of persistence
                 to the JDO implementation, which can optimize data access patterns for
                 optimal performance.


     Introduction to JDBC
     The Java Database Connectivity (JDBC) API has emerged as a key part of the Java
     2 Standard Edition (J2SE) and Java 2 Enterprise Edition (J2EE) platforms. It is the
     primary standards-based mechanism for the Java language to programmatically
     access relational databases.

     The JDBC API provides great flexibility by giving programmers direct control over
     database access and cache management. The JDBC API is a mature technology,
     enjoying very broad industry acceptance as a complete and well-understood API.

     The current version of JDBC (3.O) provides a number of much needed
     enhancements over previous versions. The JDBC 3.0 API is fully supported by DB2,


Develop DB2 applications using persistence-based frameworks                               Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                                   Page 2 of 14
ibm.com/developerWorks                                                            developerWorks®



     Version 8 and later. Features like the ability to retrieve auto-generated keys from
     database, the ability to open multiple result sets, and improved connection and
     statement pooling are notable new capabilities provided by JDBC 3.0. For example,
     Listing 1 shows a code snippet of retrieving auto-generated keys using JDBC 3.0:

     Listing 1. JDBC auto-generated keys

       Statement stmt = conn.createStatement();
       //Obtain the generated` key from query.
       stmt.executeUpdate("INSERT INTO Accounts " +
                          "(account_name, balance) " +
                          "VALUES ('Smith Savings Account', 500.00)",
                          Statement.RETURN_GENERATED_KEYS);
       ResultSet rs = stmt.getGeneratedKeys();
       if ( rs.next() ) {
           // Retrieve the auto generated key(s) i.e account_id.
           int accountIdkey = rs.getInt(1);
       }



     Introduction to Hibernate
     Hibernate is a powerful, high performance object/relational persistence and query
     service. Hibernate lets you develop persistent classes following the object-oriented
     idiom, including association, inheritance, polymorphism, composition, and
     collections. Hibernate allows you to express queries in its own portable SQL
     extension (HQL), as well as in native SQL or with an object-oriented criteria and
     example API. Unlike many other persistence solutions, Hibernate does not hide the
     power of SQL from you and guarantees that your investment in relational technology
     and knowledge is as valid as always.

     Hibernate is a professional open source project and one of the most widely-used
     and accepted frameworks as compared to any other persistence framework.
     Frameworks like Spring provide extensive support for Hibernate, whereby the Spring
     aspect-oriented programming (AOP) framework provides a way for developers to
     declaratively provide Hibernate transactions.

     Hibernate uses XML (*.hbm.xml) files to map Java classes to tables and Java
     Beans™ properties to database tables. All SQL database management systems are
     supported through JDBC. Hibernate integrates elegantly with all popular J2EE
     application servers and Web containers.


     Comparing Hibernate with JDO
     Hibernate is one of the widely used and trusted persistence frameworks and is more
     mature than specifications like JDO. Both frameworks work on providing persistence
     to directly store their Java domain model instances into the persistent store. Since


Develop DB2 applications using persistence-based frameworks                            Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                                Page 3 of 14
developerWorks®                                                                ibm.com/developerWorks



     JDO is part of the Java specification, while Hibernate is backed by open source,
     JDO will gain acceptance from different vendors over a period of time.

     In future releases of Hibernate, it would be good to have support for JDO
     implementation over its existing open source persistence framework, thus combining
     the power of JDO specification with the Hibernate trusted open source features.




     Section 3. Getting started
     In this tutorial, build a sample application that incorporates the declarative
     transaction handling of Spring AOP and the persistence backbone of Spring with
     Hibernate. Spring is an open source framework created to address the complexity of
     enterprise application development. Spring is a lightweight version of control- and
     aspect-oriented container framework. Spring framework provides AOP framework,
     JDBC DAO abstraction, integration with ORM frameworks like JDO, Hibernate, and
     IBATIS SQL Maps along with declarative transaction support and full-featured MVC
     Framework for building Web applications.

     Spring's functionality can be used with any J2EE server, and most of it can also be
     used in non-managed environments. A central focus of Spring is to allow for
     reusable business and data access objects that are not tied to specific J2EE
     services. Such objects can be reused across J2EE environments (Web or EJB),
     standalone applications, test environments, and so on, without any hassle.

     Our sample application represents a sample organization that consists of
     departments and employees. Our sample application requires a DB2 database
     named orgdb to be created, which you will see in the first step. The SampleOrgDB
     holds department and employee information. I've assumed an association of 1:N
     between the department and employees.


     Creating the sample database
     In this section, create a sample database that your sample organization application
     will use. Create a sample orgdb database that willl host department and employee
     information. To create the source tables:


            1.     At the Windows command prompt, enter db2cmd.

            2.     Create the required database by entering the following statement:
                   db2 create database orgdb


Develop DB2 applications using persistence-based frameworks                                Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                                    Page 4 of 14
ibm.com/developerWorks                                                              developerWorks®




            3.     Press Enter.

     You have now created the organization database. The tables for holding the
     department and employee application will be created by the sample Hibernate
     application.




     Section 4. Building the sample application
     Build and walk through a sample organization application using Spring AOP and
     Hibernate, which will persist a Java object in the DB2 database. The application
     allows an organization to add departments and employees belonging to those
     departments.

     Implement a DOA (data access object) pattern for database interaction. Set up
     Spring AOP's TransactionProxyFactoryBean to intercept method calls and
     declaratively apply a transaction context to the DOA for carrying out any transaction
     intensive operation.


     Setting up the JDBC DataSource and HibernateSessionFactory
     for DB2
     In the Spring framework, resources such as a JDBC DataSource or a Hibernate
     SessionFactory can be realized as beans in an application context. Application
     objects that need to access resources simply receive references to such pre-defined
     instances via bean references (more on this in the next section). In Listing 2, you
     can see an excerpt from the example application: an XML application context
     definition that shows how to set up a JDBC DataSource with a Hibernate
     SessionFactory on top of it.

     Listing 2 shows how to configure a data source bean (exampleDataSource) for
     the example application database, which is DB2. The driverClassName represents
     the Type 4 DB2 Java class (com.ibm.db2.jcc.DB2Driver), while url represents the
     location of your orgdb database (jdbc:db2://localhost:50000/orgdb).Change the
     hostname (localhost) and the port number (50000) included in the database
     connection URL to the location where you have db2 server installed. The
     Hibernate.dialect property has a value "net.sf.hibernate.dialect.DB2Dialect," which
     specifies the hibernate to use DB2 dialect, implying that you are dealing with DB2
     Database. For other database servers, this value will differ. Say, for example, that
     you are running the application on Derby -- the value would be


Develop DB2 applications using persistence-based frameworks                              Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                                  Page 5 of 14
developerWorks®                                                               ibm.com/developerWorks



     "net.sf.hibernate.dialect.DerbyDialect."

     The exampleDataSource bean is wired to the Spring Hibernate
     SessionFactory. Note that *.hbm.xml denotes the OR mapping files for the
     example application.

     Listing 2. JDBC DataSource and HibernateSessionFactory wiring


       <bean id="exampleDataSource" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName"><value>com.ibm.db2.jcc.DB2Driver</value></property>
       <property name="url"><value>jdbc:db2://localhost:50000/orgdb</value></property>
       <property name="username"><value>db2admin</value></property>
       <property name="password"><value>db2admin</value></property>
       </bean>
       <bean id="exampleHibernateProperties"
       class="org.springframework.beans.factory.config.PropertiesFactoryBean">
       <property name="properties">
       <props>
       <prop key="hibernate.hbm2ddl.auto">update</prop>
       <prop key="hibernate.dialect">net.sf.hibernate.dialect.DB2Dialect</prop>
       <prop key="hibernate.query.substitutions">true 'T', false 'F'</prop>
       <prop key="hibernate.show_sql">true</prop>
       <prop key="hibernate.c3p0.minPoolSize">5</prop>
       <prop key="hibernate.c3p0.maxPoolSize">20</prop>
       <prop key="hibernate.c3p0.timeout">600</prop>
       <prop key="hibernate.c3p0.max_statement">50</prop>
       <prop key="hibernate.c3p0.testConnectionOnCheckout">false</prop>
       </props>
       </property>
       </bean>

       <!-- Hibernate SessionFactory -->
       <bean id="exampleSessionFactory"
       class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
       <property name="dataSource"><ref local="exampleDataSource"/></property>
       <property name="hibernateProperties">
       <ref bean="exampleHibernateProperties" />
       </property>
       <!-- Must references all OR mapping files. -->
       <property name="mappingResources">
       <list>
       <value>Department.hbm.xml</value>
       <value>Employee.hbm.xml</value>
       </list>
       </property>
       </bean>



     Wiring the DAO layer
     With the data source and session factory set up, the next step is to wire in the DAO,
     in this case DepartmentDAO, to use the SessionFactory. Next, you insert
     Spring's TransactionProxyFactoryBean, which will intercept method calls to
     the application's DepartmentDAOImpl object and declaratively apply a transaction
     context to it.


Develop DB2 applications using persistence-based frameworks                               Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                                   Page 6 of 14
ibm.com/developerWorks                                                               developerWorks®



     In this example, the addDepartment method of the DepartmentDAOImpl class is
     executed as part of the transaction, with a transaction attribute of
     PROPAGATION_REQUIRED. This attribute is equivalent to TX_REQUIRED with
     respect to the EJB container. You use PROPAGATION_REQUIRED if you want the
     methods to always run in a transaction. If a transaction is already running, the bean
     method will join in that transaction, or the Spring lightweight transaction manager will
     start one for you. If you want a new transaction to always begin when the component
     services are called, use the PROPAGATION_REQUIRES_NEW attribute.

     Listing 3. Wiring together the application DAO and TransactionManager


       <!-- Pass the session factory to our DepartmentDAO -->
       <bean id="departmentDAOHelper"
       class="springexample.db2persist.hibernate.DepartmentDAOHelper">
       <property name="departmentDAO"><ref local="departmentDAOTarget"/></property>
       </bean>
       <bean id="departmentDAO"
       class="springexample.db2persist.hibernate.DepartmentDAOImpl">
       <property name="sessionFactory"><ref local="exampleSessionFactory"/></property>
       </bean>
       <bean id="transactionManager"
       class="org.springframework.orm.hibernate.HibernateTransactionManager">
       <property name="sessionFactory"><ref bean="exampleSessionFactory"/></property>
       </bean>
       <bean id="departmentDAOTarget"
       class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
       <property name="transactionManager"><ref local="transactionManager"/></property>
       <property name="target"><ref local="departmentDAO"/></property>
       <property name="transactionAttributes">
       <props>
       <prop key="addDepartment">PROPAGATION_REQUIRED</prop>
       </props>
       </property>
       </bean>


     And with that, the application wiring is done. Let's look at the source code.


     Analyzing the source code
     If you haven't already done so, download the article source code (DB2SpringHB.zip)
     from the Download section. Extract the source zip file to any location on your
     desktop, say c:\. A folder called DB2SpringHB will be created. The src\spring folder
     contains the Hibernate mapping files and Spring configuration file for the example
     application. The src\springexample\db2persist\hibernate file contains the source
     code for the application.

     Here you will find two classes, namely Department and Employee, which are
     mapped to two tables using Hibernate mapping files, using Department.hbm.xml and
     Employee.hbm.xml files. The Department class represents department information


Develop DB2 applications using persistence-based frameworks                                Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                                    Page 7 of 14
developerWorks®                                                                  ibm.com/developerWorks



     and the Employee class represents the employee information associated with the
     department. As previously mentioned, I modeled the two classes in an 1: N
     relationship, where one Department consists of multiple Employees. Listing 4
     shows the Hibernate mapping file for a Department object.

     Listing 4. Hibernate mapping file for Department object


                  <?xml version="1.0"?>
               <!DOCTYPE hibernate-mapping PUBLIC
            "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
            "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
       <hibernate-mapping>
           <class
               name="springexample.db2persist.hibernate.Department"
               table="TBL_DEPARTMENT"
               dynamic-update="false"
               dynamic-insert="false">
                  <id
                        name="id"
                        column="DEPARTMENT_ID"
                        type="java.lang.Long"
                        unsaved-value="-1"
                  >
                      <generator class="native">
                      </generator>
                  </id>

                  <set name ="employees"
                         inverse = "true"
                          outer-join="auto"
                          cascade="all-delete-orphan">
                         <key column ="EMPLOYEE_ID"/>
                         <one-to-many class="springexample.db2persist.hibernate.Employee"/>

                  </set>
                  <property
                      name="name"
                      type="string"
                      update="false"
                      insert="true"
                      column="DEPARTMENT_NAME"
                      length="60"
                      not-null="true"
                  />

            </class>
       </hibernate-mapping>


     set name="employees" and the one-to-many class tag denote the association
     between the Department and Employee. The generator class="native"

Develop DB2 applications using persistence-based frameworks                                    Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                                        Page 8 of 14
ibm.com/developerWorks                                                              developerWorks®



     implies that Hibernate will use the DB2 native identity value generation method for
     generating primary keys.


     Analyzing the DAO source code
     DepartmentDAOImpl.java represents the application DAO, which inserts
     department and employee information in the application database.
     DepartmentDAOImpl extends Spring's HibernateDaoSupport, which simplifies
     session management using the Spring HibernateTemplate. Thus you can save or
     retrieve data through the getHibernateTemplate() method. The
     getDepartmentEmployees(), shown in Listing 5, does a find of Department
     and all the employees assigned to that department using HQL with the
     getHibernateTemplate().find method.

     Listing 5. DAO implementation


       public class DepartmentDAOImpl extends HibernateDaoSupport implements DepartmentDAO{

           public void addDepartment(Department department) {
                 getHibernateTemplate().save(department);
           }
           public Department getDepartmentEmployees(Department department) {
                   Department dep = null;
                   List list = getHibernateTemplate().find("from Department department " +
                                          "where department.id = ?" ,
                                          department.getId(),Hibernate.LONG);
                     if(list.size() > 0){
                          dep = (Department)         list.get(0);
                     }
                     return dep;
           }
       }


     Now let's see the code in action!




     Section 5. Running the application
     To run the example application you must first download the Spring framework (see
     Resources) and all its dependency files. Next, extract the framework to, say c:\, to
     create a folder such as C:\spring-framework-1.2-rc2 (for the current release version).
     You must also download and extract Apache Ant before continuing (see Resources).


Develop DB2 applications using persistence-based frameworks                              Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                                  Page 9 of 14
developerWorks®                                                                ibm.com/developerWorks



     Next, extract the source code to a folder such as c:\ to create a DB2SpringHB folder.
     Next modify the build.xml file entry, replacing C:\spring-framework-1.2-rc2 with the
     location where you have installed Spring and C:\Installables\IBM\SQLLIB\java\ with
     the location where the DB2 Type 4 JDBC driver is located.

     Open up the command prompt, change the directory to DB2SpringHB, and type in
     the following at command prompt: build.

     This will build and run the CreateDepartmentEmployeeClient class, which in
     turn will create a Department class object, populate it with some data, create
     Employee objects, populate it, and add it to the Department object.

     The CreateDepartmentEmployeeClient will then call the
     DepartmentDAOHelper.addDepartment class to add the department and
     employees information. Once inserted, the CreateDepartmentEmployeeClient
     will call the DepartmentDAOHelper.getDepartmentEmployees method to get
     the department and employees information based on the deparment id. You will see
     the department name and employees information being printed on your console if
     CreateDepartmentEmployeeClient is successfully executed. You can also
     query the DB2 database to retrieve department and employee information.

     Verifying the records in the DB2 database

     To verify records in the orgdb database, carry out the following steps:

               • At the Windows command prompt, enter db2cmd
               • Enter the following statements:

               db2 connect to orgdb

               db2 select * from tbl_department

               db2 select * from tbl_employee




     You will see the records persisted in the DB2 database.

     You have now successfully tested out the sample organization application.




     Section 6. Wrap up

Develop DB2 applications using persistence-based frameworks                               Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                                   Page 10 of 14
ibm.com/developerWorks                                                           developerWorks®




     In this tutorial, you looked at various approaches of persisting data in a DB2
     database and walked through an example of building a sample application that
     incorporated the declarative transaction handling of Spring AOP and the persistence
     backbone of Spring with Hibernate to persist Java Objects in a DB2 database. This
     basic application will speed-start you on the way to building highly maintainable
     persistence-based applications for DB2 database.




Develop DB2 applications using persistence-based frameworks                          Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                              Page 11 of 14
developerWorks®                                                          ibm.com/developerWorks




     Downloads
      Description                               Name              Size     Download
                                                                           method
      Sample Hibernate Spring DB2               DB2SpringHB.zip   10KB     HTTP
      application

       Information about download methods




Develop DB2 applications using persistence-based frameworks                         Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                             Page 12 of 14
ibm.com/developerWorks                                                                  developerWorks®




     Resources
     Learn
         • "Introduction to the Spring framework" (developerWorks, June 2005): Learn
           about the basics of the Spring framework.
         • "The Spring series:" Check out this series of articles to learn about the essential
           modules of the Spring framework.
         • "An introduction to JDO 2.0 using JPOX and DB2 Universal Database"
           (developerWorks, June 2005): Learn about the JPOX implementation.
         • developerWorks Information Management zone: Find more resources for DB2
           UDB developers and administrators.
         • Stay current with developerWorks technical events and webcasts.
     Get products and technologies
         • Download DB2 UDB Database 8.2 from developerWorks (either Enterprise
           Server Edition or DB2 Express).
         • Download the Spring framework.
         • Download Apache Ant.
         • Build your next development project with IBM trial software, available for
           download directly from developerWorks.
     Discuss
         • Participate in the discussion forum for this content.
         • Participate in developerWorks blogs and get involved in the developerWorks
           community.



     About the author
     Naveen Balani
                Naveen Balani spends most of his time designing and developing
                J2EE-SOA based frameworks and products. He has written various
                articles for IBM developerWorks covering such topics as Semantic
                Web, ESB, SOA, JMS, Axis, Spring Series, Web services
                Architectures,Spring Series,CICS, AXIS, DB2, XML Extender, DB2
                Content Manager, WebSphere Studio, MQSeries, Java Wireless
                Devices and DB2 Everyplace for Palm, J2ME, MIDP, Java-Nokia,
                Visual Studio .NET, and wireless data synchronization.



Develop DB2 applications using persistence-based frameworks                                 Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                                     Page 13 of 14
developerWorks®                                               ibm.com/developerWorks




     Trademarks




Develop DB2 applications using persistence-based frameworks              Trademarks
© Copyright IBM Corporation 2006. All rights reserved.                  Page 14 of 14

				
DOCUMENT INFO
Shared By:
Tags:
Stats:
views:12
posted:10/3/2012
language:
pages:14
Azeem Yaseen Azeem Yaseen Senior Consultant http://azimyasin.wordpress.com
About