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.

 

No comments:

Post a Comment