Hibernate 3 Adds XML-Relational Persistence

ibernate has taken the IT world by surprise with its easy-to-use, high-performance, and sophisticated features for object-relational (OR) persistence. The most recent version of Hibernate (version 3, released on March 29) brings an important new feature to the product API: XML persistence. With Hibernate 3, Java application developers can conveniently persist XML documents into relational databases.

This new feature definitely should appeal to existing Hibernate developers because it follows the same persistence methods as POJOs (plain old Java objects), requiring a minimal learning curve. The convenience of XML persistence should appeal to new users as well. This article describes the Hibernate 3 persistence method.

Why XML Persistence Is Important
Most of the larger commercial databases support some form of native XML persistence. Since XML persistence is a relatively new mechanism?even for larger vendors, the standards in this field are still emerging. As a result, in order to integrate the ubiquitous relational persistence mechanisms with increasingly prevalent XML solutions, an architect must either resort to vendor-specific features or implement a custom XML persistence framework. Neither is a particularly attractive option. Vendor-specific features are unpopular because they can lead to vendor lock-in, and a custom framework implementation can be laborious and lengthy, resulting in code that is hard to maintain.

As is the case with OR persistence, Hibernate XML persistence is as a natural solution for this scenario. It is portable across all of the relational platforms that Hibernate supports (i.e., virtually all true relational platforms), allowing for the freedom to migrate objects and XML-based application and integration solutions without worrying about the underlying relational implementation.

Architectural Specifics
Hibernate is a nicely architected framework that seamlessly utilizes native environments without any special interventions or installations by the user. Switching from one database to another is usually a matter of changing a driver and configuring Hibernate (one-line configuration setting) to use one database dialect versus another.

Hibernate utilizes the dom4j framework for XML parsing and manipulation. To fully utilize Hibernate’s XML features, you must get familiar with dom4j. Most likely, you will find dom4j easier to use than JAXP and JAXP-compliant XML parsers that are supplied through Java. It has a very flat learning curve and you can start using the Hibernate XML persistence features effectively with minimal dom4j knowledge.

A Real World Example: Price Catalog Synchronization
A common e-business scenario should demonstrate the usefulness of XML-relational persistence mechanisms. Consider an example in which XML integrates priced product catalogs between online merchants and vendors.

The electronic catalog contains the priced product lists. The online store sells the products, which it manages through its own inventory (similar to Amazon’s relationship with Toys-R-Us and sporting goods stores). In order to accurately and efficiently reflect price updates, the online merchant needs to receive frequent product pricing feeds. It receives these feeds as an XML document that looks similar to this:

	"3" sku="100101">	         		Athlete mode body fat scale		100.00		60.00			"4" sku="100102">		Thermometer		20.00		11.00	

The comprehensive master product price list is stored on the database as follows:

CREATE TABLE PRODUCT(  id INT UNIQUE NOT NULL,  description VARCHAR(45) NOT NULL,  sku VARCHAR(45) UNIQUE NOT NULL,  list_price FLOAT,  base_price FLOAT,  order_price FLOAT,  CONSTRAINT PK_PRODUCT PRIMARY KEY (id ))

The online store presents a Web representation of the priced catalog through the existing OR mapping, where the priced products are represented as demo.Product Java objects:

/** Product object represents the priced catalog item. */public class Product {		int id;	String sku;	String description;	Double listPrice;	Double basePrice;	Double orderPrice;

These objects also are mapped as the following (the column names are listed for clarity, even though Hibernate can auto-map the properties to column names if they match):

"1.0"?>"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">"demo">"Product" 	table="product"	node="product">	"id" 		type="int"		node="@prod_id"		column="id">		"sku" node="@sku" column="sku" not-null="true"/>	"description" node="description" column="description"  not-null="true"/>		"listPrice" node="list_price" column="list_price" />	"basePrice"  node="drop_price" column="base_price"/>	"orderPrice" column="order_price"/>

In this scenario, Hibernate’s XML-relational persistence comes in very handy. As the e-business application receives XML feeds containing the product price updates, it persists them into the product database utilizing Hibernate’s XML persistence mechanisms. Hibernate offers several XML persistence alternatives, including the Hibernate saveOrUpdate method:

		document = saxReader.read(inputXML);		List users = document.selectNodes("//product");		try {			Session session = HibernateUtil.sessionFactory.openSession();			Transaction transaction = session.beginTransaction();			Session dom4jSession = session.openSession(EntityMode.DOM4J);			Iterator iter = users.iterator();			while (iter.hasNext()) {				Object next = iter.next();				dom4jSession.saveOrUpdate("demo.Product", next );			}// end while			transaction.commit();			session.close();

XML Mapping Syntax
The mapping file that the previous example used is different from the Hibernate 2 mapping file. Hibernate 3 introduced several new mapping types specific to XML persistence.

The central new mapping attribute is a node, which relates either to the element within an XML document or to the attributes in the document that are to be mapped.

A “node” can represent a mapping of the following:

  • "element-name": In the case study, this would be expressed as a node=”product” for a element.
  • "@attribute-name": In the example, node=”@sku” would map to an XML attribute .
  • Period ("."): This maps to the parent of the element (like as a parent of the ).
  • "element-name/@attribute-name": These map to the attribute of the named element (product/@sku).

XML Persistence Not Hibernate’s Main Mission
Release 3 of the Hibernate framework effectively closes the cycle on the most common persistence methods available today (excluding only LDAP). Java community now has a framework that provides an efficient and consistent method for effortless OR and XML persistence.

With that in mind, understanding the Hibernate project’s mission is important. Even though the Hibernate 3 XML features are highly useful and attractive, they are not meant to replace the most popular XML marshalling or transformation frameworks. Despite a very comprehensive OR mapping solution, Hibernate is not expected to grow into a major XML manipulation framework (per Hibernate author Gavin King, TheServerSide Java Symposium 2005).

For that reason, you should take the XML persistence features as helpful extensions to the already powerful Hibernate framework, which enable you to easily incorporate another contemporary data representation mechanism into your application. If you have to deal with intricate integration and transformation scenarios, however, look into XML-specific frameworks.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Related Posts

DevX is the leading provider of technical information, tools, and services for professionals developing corporate applications.

Join Our Newsletter

Subscribe to receive our latest blog posts directly in your inbox!

© All Rights Reserved.