I made a change in the blogger configuration to ease the later work when blogging. It is possible that older entries are not correctly formatted.

Showing posts with label "O/R Mapping". Show all posts
Showing posts with label "O/R Mapping". Show all posts

Monday, 22 September 2008

Hibernate

Hibernate is an OR-Mappping. Mostly adapted the examples from the chapter 2 of Java Persistence with Hibernate
Second Edition of Hibernate in Action
Christian Bauer and Gavin King
November, 2006 | 880 pages
ISBN: 1-932394-88-5
The goal is to map the objects created by a object programming language such as Java to a relational database in order to provide persistent objects, i.e object which can be stored on disk and which do not disappear when the virtual machine shutdowns. Hibernate performs the mapping using configurations files in xml (or other). Here is an example of XML file for a mapping called tasks.hbm.xml:
<?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 <hibernate-mapping>
   <class
     name="mytasks.Task"
      table="TASKS">
    <id
       name="id"
       column="TASK_NAME">
       <generator class="increment"/>
    </id>
    <property
        name="name"
        column="Task_NAME"/>
    <many-to-one
       name="nexttask"
       cascade="all"
       column="SPOUSE_ID"
       foreign-key="FK_NEXT_TASK"/>
   </class>
</hibernate-mapping>
a class like:
class Task {
   private String name;
   private Task nexttask;
}
package mytasks; import org.hibernate.*;
import persistence.*;
import java.util.*;
public class TaskExample {
     public static void main(String[] args) {
         // First unit of work
         Session session =
          
        HibernateUtil.getSessionFactory().openSession();
         Transaction tx = session.beginTransaction();
         Task firsttask = new Task("Learn Hibernate");
         Long meberId = (Long) session.save(firsttask);
         tx.commit();
         session.close();
         // Second unit of work
         Session newSession =                     HibernateUtil.getSessionFactory().openSession();
         Transaction newTransaction =            newSession.beginTransaction();
         List tasks =            newSession.createQuery("from Task m order by m.name asc").list();
         System.out.println( tasks.size() + " Task(s) found:" );
         for ( Iterator iter = members.iterator(); iter.hasNext(); ) {
           Tasks task = (Task) iter.next();
           System.out.println( task.getName() );
         }
         newTransaction.commit();
         newSession.close();
         // Shutting down the application
         HibernateUtil.shutdown();
     }
}
It is possible to set the configuration file for the session factory using new Configuration().configure(<locationof config file>); for example:
SessionFactory sessionFactory = new Configuration()      .configure("/persistence/tasks.cfg.xml")      .buildSessionFactory();
calling new Configuration().configure(); would look for a file called: hibernate.properties in the class path directory outside of any package. the Hibernate Configuration file:
<!DOCTYPE hibernate-configuration SYSTEM "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
     <session-factory>
       <property name="hibernate.connection.driver_class">
         org.postgresql.Driver        </property>
       <property name="hibernate.connection.url">
         jdbc:postgresqll://localhost
       </property>
       <property name="hibernate.connection.username">
         sa
       </property>
       <property name="hibernate.dialect">
         org.hibernate.dialect.HSQLDialect
       </property>
     <!-- Use the C3P0 connection pool provider -->
       <property name="hibernate.c3p0.min_size">5</property>
         <property name="hibernate.c3p0.max_size">20</property>
         <property name="hibernate.c3p0.timeout">300</property>
         <property name="hibernate.c3p0.max_statements">50</property>
         <property name="hibernate.c3p0.idle_test_period">3000</property>
         <!-- Show and print nice SQL on stdout -->
         <property name="show_sql">true</property>
         <property name="format_sql">true</property>
         <!-- List of XML mapping files -->
         <mapping resource="mytasks/tasks.hbm.xml"/>
     </session-factory>
</hibernate-configuration>

Note the use of a certain number of configuration entries:

  • the Hibernate connection pool provider: here the C3PO-connection-pool-provider
  • the hibernate dialect used, here the HSQLDialect
  • the connection information: drivers, url and username
  • the mapping file

There are a number of other possibilities to configure Hibernate.

Thursday, 13 December 2007

First Start to Hibernate

In the series of new technologies which I should get my hands on and about which I wish to get an overview Hibernate is an important candidate.

First of all Hibernate is an Object/Relation Mapping framework, this means that it is used to create maps between object oriented structures and relational databases. The main goal is to keep the object in a running system as persistent as possible with the data present in the database in order to ensure consistency in the data. Another important point is also the efficiency of querying and the optimized use of resources.

In Hibernate this is managed through the use of a mapping defined using XML configuration files. The mappings are stored in a file looking like that:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
[...]
</hibernate-mapping>

A mapping as the following shape:

<class name="myaddressbook.model.Person" table="PERSONS">
....
</class>
where the name is the java name of the class, whereas PERSONS is th name of the relational table of this class.

the fields of a class Person of the sort:

package myaddressbook.model.Person;

class Person {

Long id;
String name;
Date birthday;

// plus the corresponding getters/setters
}
would look like:

<id name="id" column="PERSON_ID">
           <generator class="native"/>
       </id>
       <property name="birthday" type="timestamp" column="BIRTHDAY"/>
       <property name="name"/>


finally the complete file should be under: person.hbm.xml at the place where the file is found.

For the configuration of Hibernate, it is important to set the information about the database. For this, there are different possibilities:

  • a properties file
  • an XML configuration files
  • or using Java to set the information