December 22, 2014
Hot Topics:

An Introduction to Object-Relational Mapping with Hibernate

  • August 5, 2004
  • By Olexiy & Alexander Prokhorenko
  • Send Email »
  • More Articles »

At last, we will start using Hibernate. To keep object in a database, it is necessary to execute the following steps (actions):

  • Create an object of the Product class
  • Receive net.sf.hibernate.SessionFactory with the use of net.sf.hibernate.cfg.Configuration, right at the beginning of the application.
  • Open a net.sf.hibernate.Session session by calling the SessionFactory.openSession() method.
  • Keep an object of the Product class and close the session.

However, before you start these steps, you should define some configuration files with which Hibernate will "know" where it is necessary to keep your objects and how your objects will be displayed in the chosen storehouse (the database table).

The first configuration file is a hibernate.properties file. This file defines which database we want to us, a name of the user and the password, and a set of other options. In our case, the database will be MySQL, and the hibernate.properties file will contain the next lines:

hibernate.connection.username=green
hibernate.connection.password=
hibernate.connection.url=jdbc:mysql://localhost/hibernate
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect

The next necessary file is Product.hbm.xml. It is an XML file that defines how Java objects are kept in a database. In this file, we determine the data in what table of our database and how it will be written down, what field in which column of the table, and so forth. Here is the code for our Product.hbm.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
   PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
   <class name="Product" table="products">
      <id name="id" type="string" unsaved-value="null">
         <column name="id" sql-type="char(32)" not-null="true"/>
         <generator class="uuid.hex"/>
      </id>
      <property name="name">
         <column name="name" sql-type="char(255)" not-null="true"/>
      </property>
      <property name="price">
         <column name="price" sql-type="double" not-null="true"/>
      </property>
      <property name="amount">
         <column name="amount" sql-type="integer" not-null="true"/>
      </property>
   </class>
</hibernate-mapping>

The line <class name = "Product" table = "products"> means that we are going to display a class with the name Product in the table products.

The <id> element and its affiliated elements set the communication between our Java class and a database.

The <property> elements define in what columns each of fields will be kept, and also its type, a name, etc.

The <generator class = "uuid.hex"/> element, at first glance, is not understandable. Knowing that is one of the affiliated elements of an <id> element, its purpose becomes clearer: Because our application does not know how the data will be kept in a database, the substitute key is necessary for us. This key will not have any value in the business logic of the application. It only helps Hibernate manipulate objects. Again, a created object of the Product class has no certain ID—Hibernate will create it for us. In our case, we have chosen UUID lines; however, there are many various predetermined ID generators. Besides, you also can write you own. For more detailed information, I suggest you to take a look at the documentation delivered with Hibernate.

Storing New Products

Now that we have these two files, we can create an algorithm for storing the Product class in a database with the help of the following code:

import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;

// Usage:
// java InsertProduct <title> <amount> <price>
public class InsertProduct {
   public static void main(String[] args) throws Exception {
      Product p = new Product();
      p.setName(args[0]);
      p.setAmount(Integer.parseInt(args[1]));
      p.setPrice(Double.parseDouble(args[2]));

      Configuration cfg = new Configuration().addClass(Product.class);
      SessionFactory sf = cfg.buildSessionFactory();

      Session sess = sf.openSession();

      Transaction t = sess.beginTransaction();
      sess.save(p);
      t.commit();
      sess.close();
   }
}

To run our program and store a new object, use this:

java InsertProduct Book 100 600

With the help of the MySQL console client (mysql.exe), you can take a look at the products table's contents. Use the following commands:

USE hibernate;
SELECT * FROM products;

Then you supposed to see table with the only one record:

ID                               | NAME  | PRICE | AMOUNT |
3f138041f947f4320ff90764f8340f01 | Book  | 600   | 100    |

Now you are convinced that the information on the object of the Product class has been successfully stored in our database, and thus we have not written any SQL expression.





Page 2 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel