如何使用带注释的Hibernate从数据库导出数据并将其存储在XML文件中。
请告诉我任何可以帮助我的方法或教程!
答案 0 :(得分:3)
准备数据库:
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();
}
}
我们将数据库保存到XML文件“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());
}
}
现在我们可以清理数据库并尝试从XML文件中重新创建它:
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());
}
}