18.3. 操作XML数据

让我们来读入和更新应用程序中的XML文档。通过获取一个dom4j会话可以做到这一点:

  1. Document doc = ....;
  2. Session session = factory.openSession();
  3. Session dom4jSession = session.getSession(EntityMode.DOM4J);
  4. Transaction tx = session.beginTransaction();
  5. List results = dom4jSession
  6. .createQuery("from Customer c left join fetch c.accounts where c.lastName like :lastName")
  7. .list();
  8. for ( int i=0; i<results.size(); i++ ) {
  9. //add the customer data to the XML document
  10. Element customer = (Element) results.get(i);
  11. doc.add(customer);
  12. }
  13. tx.commit();
  14. session.close();
  1. Session session = factory.openSession();
  2. Session dom4jSession = session.getSession(EntityMode.DOM4J);
  3. Transaction tx = session.beginTransaction();
  4. Element cust = (Element) dom4jSession.get("Customer", customerId);
  5. for ( int i=0; i<results.size(); i++ ) {
  6. Element customer = (Element) results.get(i);
  7. //change the customer name in the XML and database
  8. Element name = customer.element("name");
  9. name.element("first-name").setText(firstName);
  10. name.element("initial").setText(initial);
  11. name.element("last-name").setText(lastName);
  12. }
  13. tx.commit();
  14. session.close();

将这一特色与Hibernate的replicate()操作结合起来对于实现的基于XML的数据导入/导出将非常有用.