Retrieving an XML Document from Database
Next, retrieve the data you've stored in the database table as an XML document. As in the previous section, create a Configuration object and add the mapping file catalog.hbm.xml to the Configuration object:
Configuration config = new Configuration();
config.addFile("catalog.hbm.xml");
Create a SessionFactory object from the Configuration object and open a Session object from the SessionFactory:
SessionFactory sessionFactory = config.buildSessionFactory();
session = sessionFactory.openSession();
Start a new session in DOM4J entity mode:
Session dom4jSession = session.getSession(EntityMode.DOM4J);
Begin a new transaction:
tx = session.beginTransaction();
Next, construct an XML document with data from Catalog. First, create a Document object using the static method createDocument() (of the DocumentHelper class). Add the root element catalogs to the Document object:
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement("catalogs");
Create a Hibernate Query Language (HQL) query to select data from the table. HQL syntax is similar to SQL. The SELECT clause is not required for a query. The FROM clause in HQL is specified with the entity name instead of the database table:
String hqlQuery ="FROM Catalog";
Create a Query object with the createQuery(hqlQuery) method of the Session object and subsequently obtain the query results as a List using the list() method. The HQL query is run using the Session object in DOM4J entity mode:
List results = dom4jSession.createQuery(hqlQuery).list();
Iterate over the List and obtain the Element objects corresponding to the catalog node. A row in Catalog corresponds to a catalog element node in the XML document which is in turn mapped to the database table. Add the catalog nodes to the root element of the Document object:
for (int i = 0; i < results.size(); i++) {
Element catalog = (Element) results.get(i);
rootElement.add(catalog);
}
Output the Document object using an XMLWriter object:
XMLWriter output = new XMLWriter(new FileWriter(
new File("c:/catalog/catalog.xml")));
output.write(document);
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.