Sunday, April 27, 2008

Learnings: Hibernate basics and QuickStart

General Information

Hibernate is a powerful, ultra-high performance object/relational persistence and query service for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework. The Hibernate Query Language, designed as a "minimal" object-oriented extension to SQL, provides an elegant bridge between the object and relational worlds. Hibernate also allows you to express queries using native SQL or Java-based Criteria and Example queries. Hibernate is now the most popular object/relational mapping solution for Java.

Who should use Hibernate?

Intended users for Hibernate are developers trying to separate the regular code from the database code. Hibernate provides a cleaner way of separating the two layers, leaving the user to interact with just java-beans.

Installation

 

How can I obtain Hibernate in Linux?

Select Hibernate component in the installer. The required libraries should be installed into <install.root>/lib/hibernate directory.

What do I need to use Hibernate?

The library files (jar files) installed with spike-installer are to be used to write specific applications.

How do I install Hibernate in Linux?

1.       Installation from Download

o                   Download the shell script installer to a temporary location and run. You must be root to install SpikeSource Release 1.6.0. The file is of the form corestack-<version>.<architecture>-<platform>.bin, for example, % sh <download directory>/corestack-1.4 .ix86-fedora1.bin.

2.       Installation from CD

o                   Open a shell window and invoke the shell script installer on the cdrom

o                   % cd /mnt/cdrom

o                   % sh ./corestack-1.4 .ix86-fedora1.bin.

Choose to install Hibernate during the initial steps of installation.

After installation the directory/file layout will be:

<OSS_HOME> (default is /opt/oss)

install root

etc/rc.d

rc.hibernate run-command script (for post-install usability check)

lib/hibernate

hibernate core and runtime files

How can i uninstall Hibernate in Linux?

% cd <OSS_HOME>
% source ./env.sh
% su
% openpkg rpm -e --nodeps hibernate (--nodeps will remove a product without removing the installed dependencies. To perform a full uninstall, where dependencies are automatically removed where no conflict exists, remove the --nodeps parameter option.)

How can i install / uninstall Hibernate in Windows?

Installing / Uninstalling Hibernate is done automatically when a database stack is installed / uninstalled

After installation the directory/file layout will be:

<OSS_HOME> (default is C:\Program Files\SpikeSource\oss)

install root

hibernate\

jar files needed for Hibernate.

 

Configuration

 

Hibernate can be configured in 2 ways:

Property file:

example file attached: hibernate.properties

Important parameters are:

    //dialect to be used
    hibernate.dialect net.sf.hibernate.dialect.HSQLDialect
    //driver used
    hibernate.connection.driver_class org.hsqldb.jdbcDriver
    //username
    hibernate.connection.username sa
    hibernate.connection.password secret
    hibernate.connection.url jdbc:hsqldb:hsql://localhost
    hibernate.connection.url jdbc:hsqldb:test
    hibernate.connection.url jdbc:hsqldb:.
    


Xml file:
 example file attached: hibernate.cfg.xml

 <hibernate-configuration>

    <session-factory>

        <property name="connection.url">jdbc:mysql://yangtze/test</property>

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="connection.username"></property>

        <property name="connection.password"></property>

        <property name="connection.pool_size">12</property>

  

        <property name="show_sql">false</property>

        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>

  

        <!-- Mapping files -->

        <!--mapping resource="Cat.hbm.xml"/-->

        <mapping resource="dis_forums.hbm.xml"/>

    </session-factory>

  </hibernate-configuration>

Programmatic configuration:
http://www.hibernate.org/hib_docs/reference/en/html/session-configuration.html

 

Getting Started

 

Hibernate is a simple tool to use, and the configurations are simple.

Example: Populate a 'Cat database' and query for results

1.       Create the mapping xml - Cat.hbm.xml

2.              <hibernate-mapping>
3.                  <class name="Cat" table="CAT">
4.                      <!-- the unique identifier for the cat -->
5.                      <id name="id" type="string" unsaved-value="null" >
6.                          <column name="CAT_ID" sql-type="char(32)" not-null="true"/>
7.                          <generator class="uuid.hex"/>
8.                      </id>
9.           
10.                  <!-- name for the cat -->
11.                  <property name="name">
12.                      <column name="NAME" sql-type="varchar(16)" not-null="true"/>
13.                  </property>
14.       
15.                  <!-- Sex -->
16.                  <property name="sex" type="char"/>
17.       
18.                  <!-- Weight -->
19.                  <property name="weight" type="float"/>
20.              </class>
21.          </hibernate-mapping>
            

22.    Register the mapping xml in the hibernate.cfg.xml file

23.          <hibernate-configuration>
24.              <session-factory>
25.       
26.                  ... other parameters ...
27.       
28.                  <!-- Mapping files -->
29.                  <mapping resource="Cat.hbm.xml"/>
30.       
31.              </session-factory>
32.          </hibernate-configuration>
        

33.    Getting hibernate session: HibernateUtil.java

34.       
35.          public class HibernateUtil {
36.              private static final SessionFactory sessionFactory;
37.       
38.              static {
39.                  try {
40.                      // this will pickup the hibernate.cfg.xml by default.
41.                      // you can specify a different file-name to be used,
42.                      // or build the configuration programatically
43.                      sessionFactory = new Configuration().configure().buildSessionFactory();
44.                  } catch (HibernateException ex) {
45.                      throw new RuntimeException("Exception building SessionFactory: "
46.                              + ex.getMessage(), ex);
47.                  }
48.              }
49.       
50.              public static final ThreadLocal session = new ThreadLocal();
51.              public static Session currentSession() throws HibernateException {
52.                  Session s = (Session) session.get();
53.                  // Open a new Session, if this Thread has none yet
54.                  if (s == null) {
55.                      s = sessionFactory.openSession();
56.                      session.set(s);
57.                  }
58.                  return s;
59.              }
60.       
61.              public static void closeSession() throws HibernateException {
62.                  Session s = (Session) session.get();
63.                  session.set(null);
64.                  if (s != null)
65.                      s.close();
66.              }
67.          }
        

68.    Saving a cat

69.          public void addCat(String name, char sex, float weight) {
70.              Session session = HibernateUtil.currentSession();
71.              Transaction tx= hibernateSession.beginTransaction();
72.       
73.              Cat cat = new Cat();
74.              cat.setName("NewCat" + suffix);
75.              cat.setSex('F');
76.              cat.setWeight(5.5);
77.       
78.              hibernateSession.save(cat);
79.              tx.commit();
80.              HibernateUtil.closeSession();
81.          }
            

82.    Query for cat

83.          public void queryCat() throws Exception {
84.              Session hibernateSession = HibernateUtil.currentSession();
85.              Transaction tx= hibernateSession.beginTransaction();
86.              String selectQuery = "select cat from Cat as cat";
87.              Query query = hibernateSession.createQuery(selectQuery);
88.              System.out.println("Results:");
89.              for (java.util.Iterator it = query.iterate(); it.hasNext();) {
90.                  Cat cat = (Cat) it.next();
91.                  System.out.println(cat.getName());
92.                  Iterator nickNames = cat.getNickNames().iterator();
93.                  while (nickNames.hasNext()) {
94.                      System.out.println("    " + nickNames.next());
95.                  }
96.                  //hibernateSession.delete(cat);
97.              }
98.              tx.commit();
99.              HibernateUtil.closeSession();
100.      }
            

101. Classpath

The class path should point to Cat.hbm.xml, hibernate.cfg.xml, hibernate2.jar and the runtime libraries.

For more implementation details, please refer to the example.

To test if hibernate is installed correctly, and is usable, follow the steps

    % cd <OSS_HOME>
    % su
    % source ./env.sh
    % openpkg rc hibernate status
    

The output hibernate_usable="yes" should confirm that hibernate is installed properly.

 

Thursday, April 17, 2008

What is the difference between ResultSet and RowSet in JDBC

A ResultSet maintains a connection to a database and because of that it can’t be serialized and also we cant pass the Resultset object from one class to other class across the network.

RowSet is a disconnected, serializable version of a JDBC ResultSet and also the RowSet extends the ResultSet interface so it has all the methods of ResultSet. The RowSet can be serialized because it doesn’t have a connection to any database and also it can be sent from one class to another across the network.

More on RowSet:

A RowSet can be * connected * or *disconnected* 
A *disconnected* rowset gets a connection to a data source in order to fill itself with data or to propagate changes in data back to the data source, but most of the time it does not have a connection open. While it is disconnected, it does not need a JDBC driver or the full JDBC API, so its footprint is very small. Thus a rowset is an ideal format for sending data over a network to a thin client.  
A connected RowSet is like a wrapper around the ResultSet. 
Implementation: 
A CachedRowSet class—a disconnected rowset that caches its data in memory; not suitable for very large data sets, but an ideal way to provide thin Java clients, such as a Personal Digital Assistant (PDA) or Network Computer (NC), with tabular data  
A JDBCRowSet class—a connected rowset that serves mainly as a thin wrapper around a ResultSet object to make a JDBC driver look like a JavaBeans component  
A WebRowSet class—a connected rowset that uses the HTTP protocol internally to talk to a Java servlet that provides data access; used to make it possible for thin web clients to retrieve and possibly update a set of rows

 

For example when we are querying the database using the ResultSet object, as it is connected to the database until the object is open and it does not contain all the data from your query. Since it has a connection to the database, when you run the next() method if the ResultSet needs more data it can go to the database and get it. The RowSet can not do that since it is not connected to the database so it must load and hold all the data from your query as soon as you run the execute() method. If your query returns a lot or rows you could encounter very slow processing and out of memory errors. However, if the number of rows to be returned is a reasonable number then a RowSet can be used

What are differences between and in Struts?

<bean:message>: This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle. 
<bean:message key=”label.search.name”/>

 


<bean:write>: This tag is used to output property values from a bean. <bean:write> is a commonly used tag which enables the programmers to easily present the data.
<bean:write name=”student” property=”age”/>

Getting a RequestDispatcher from a ServletRequest VS ServletContext

 

1)       request.getRequestDispatcher("/TestCalendar.jsp");

This will take the relative URL referred to Current Request.

 

 

2)       getServletContext().getRequestDispatcher("/jsp/TestCalendar.jsp");

This will take URL from context root. So if you are referring path in this method, always start with a Slash.

 

Struts DynaActionForm-Basics

DynaActionForm is specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean.

 

DynaActionForm eliminates the need of FormBean class and now the form bean definition can be written into the struts-config.xml file. So, it makes the FormBean declarative and this helps the programmer to reduce the development time.

 

1)       Adding DynaActionForm Entry in struts-config.xml

<form-bean name="DynaAddressForm"   
         type="org.apache.struts.action.DynaActionForm">
         <form-property name="name" type="java.lang.String"/>

2)       In action class, cast it DynaActionForm addressForm = (DynaActionForm)form;

3)      Use get function , String name=addressForm.get("name")