Java Reference
In-Depth Information
System.out.println("Preparing the Session objects");
Session session = sessionFactory.openSession();
Session xmlSession = session.getSession(EntityMode.DOM4J);
System.out.println("Reading the catalog from the database");
session.beginTransaction();
export(xmlSession,root,"from User");
export(xmlSession,root,"from Advert");
export(xmlSession,root,"from Category");
session.getTransaction().commit();
session.close();
System.out.println("Dumping the catalog to a file");
BufferedWriter writer = new BufferedWriter(new FileWriter("catalog.xml"));
document.write(writer);
writer.flush();
writer.close();
System.out.println("Done.");
}
public static void export(Session xmlSession,Element root,String hql) {
Query query = xmlSession.createQuery(hql);
List categories = query.list();
Iterator cit = categories.iterator();
while(cit.hasNext()) {
Element element = (Element)cit.next();
root.add(element);
}
}
}
The code in Listing A-8 generates the catalog.xml file shown in Listing A-9. Note how the
node attributes in the mapping file correspond to the positions of the elements and attributes
in the exported XML file. Note also how setting the embed-xml attribute to false substitutes the
id value for the generated XML in the elements at the catalog/category/advert path.
Listing A-9. The XML Exported by Hibernate
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<user id="1" name="dave" password="dodgy"/>
...
<advert id="1" user="1">
<content>48k original box and packaging</content>
<title>Sinclair Spectrum for sale</title>
</advert>
...
Search WWH ::




Custom Search