Tuesday, February 20, 2007

How to store XML in database

Imagine that you have a lot of XML documents and you need to store them in RDBMS.

Using OOP approach is preferred. So, lets take JAXB - now we can work with our XML as with object hierarchy. Storing some _object_ in RDBMS means using some ORM. Let it be Hibernate. What is the next ?

Solution is Hyperjaxb 2. It's relational persistence extension of the JAXB RI. With this simple Ant target you can generate binding from XML Schema or DTD and hibernate mappings as well :

<target name="generate-sources">
<taskdef
name="xjc"
classname="com.sun.tools.xjc.XJCTask"
classpathref="classpath"/>
<xjc target="src" extension="true">
<arg line="
-dtd
-Xequals
-XhashCode
-Xhyperjaxb2"/>
<schema dir="xml/schema">
<include name="**/*.dtd"/>
</schema>
</xjc>
</target>

In this snip of code DTD is used instead of XML schema (-dtd flag is added).
After "ant generate-sources" all the classes and hibernate mappings are placed in src dir. This tool can simplify my life and save some time for rest :)

This is probably one more reason of using mainstream (Hibernate) - third party addons.

No comments: