Java Reference
In-Depth Information
<category id="1" name="retro">
<advert>1</advert>
<advert>3</advert>
</category>
...
</catalog>
Importing XML Entities
The session in Dom4J entity mode can be used to import data into Hibernate as well as export
it. The process is really just the export process in reverse—although there is one gotcha to be
aware of: by default, the entity names will be assumed to be the same as the element nodes
that you attempt to persist from the Dom4J document. Unless your node attributes in the
mapping files correspond exactly with the entity names used in the mapping files, calls to the
session will need to include the explicit entity name being saved.
Listing A-10 shows an example of a workaround for this issue, in which a hard-coded map
translates short element names into full entity names, and the version of the save() method
that takes an entity name string is invoked. When the class elements' node attributes corre-
spond exactly with entity names, this sort of approach becomes unnecessary.
Listing A-10. Importing Entities from an XML Document
package sample.xml;
import java.util.*;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
public class ImportXML {
private static final SessionFactory sessionFactory = new Configuration()
.configure().buildSessionFactory();
public static void main(String[] args) throws Exception {
System.out.println("Preparing the DOM Document");
SAXReader reader = new SAXReader();
Document document = reader.read("catalog.xml");
System.out.println("Preparing the Session objects");
Session session = sessionFactory.openSession();
Session xmlSession = session.getSession(EntityMode.DOM4J);
System.out.println("Importing the catalog from the document");
session.beginTransaction();
Search WWH ::




Custom Search