开发者

Export data from database into XML file

How can I export data from database and store it in an XML file using Hibernate with annotation.

Please tell me a开发者_C百科ny way or tutorial that can help me!


Xml Import-Export In Java

Prepare Database:

SerializeExample.java: setObjects
private static void setObjects()  {
    new File(DB4O_FILE_NAME).delete();
    ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME);
    try  {
      Car car = new Car("BMW", new Pilot("Rubens Barrichello"));
      container.store(car);
      car = new Car("Ferrari", new Pilot("Michael Schumacher"));
      container.store(car);
    } finally  {
      container.close();
    }
  }

We will save the database to XML file "formula1.xml":

SerializeExample.java: exportToXml
private static void exportToXml()  {
    XStream xstream = new XStream(new DomDriver());
    try  {
      FileWriter xmlFile = new FileWriter(XMLXML_FILE_NAME);
      ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME);
      try  {
        ObjectSet result = container.query(Car.class);
        Car[] cars = new Car[result.size()];
        for (int i = 0; i < result.size(); i++)  {
          Car car = (Car) result.next();
          cars[i] = car;
        }
        String xml = xstream.toXML(cars);
        xmlFile.write("<?xml version=\"1.0\"?>\n" + xml);
        xmlFile.close();
      } finally  {
        container.close();
      }
    } catch (Exception ex)  {
      System.out.println(ex.getMessage());
    }
  }

Now we can clean the database and try to recreate it from the XML file:

SerializeExample.java: importFromXml
private static void importFromXml()  {
    new File(DB4O_FILE_NAME).delete();
    XStream xstream = new XStream(new DomDriver());
    try  {
      FileReader xmlReader = new FileReader(XMLXML_FILE_NAME);
      Car[] cars = (Car[]) xstream.fromXML(xmlReader);
      ObjectContainer container;
      for (int i = 0; i < cars.length; i++)  {
        container = Db4o.openFile(DB4O_FILE_NAME);
        try  {
          Car car = (Car) cars[i];
          container.store(car);
        } finally  {
          container.close();
        }
      }
      container = Db4o.openFile(DB4O_FILE_NAME);
      try  {
        ObjectSet result = container.query(Pilot.class);
        listResult(result);
        result = container.query(Car.class);
        listResult(result);
      } finally  {
        container.close();
      }
      xmlReader.close();
    } catch (Exception ex)  {
      System.out.println(ex.getMessage());
    }
  }

Sample Code

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜