Link to home
Start Free TrialLog in
Avatar of BrijBhasin
BrijBhasin

asked on

Hibernate XMl persistence

Hi,
  I found this article that talks about XML persistence with Java.
http://www.devx.com/Java/Article/27896/0/page/2
how would I change this code to read an xml file that resides in the same directory as my java file.

document = saxReader.read(inputXML);
Avatar of Mick Barry
Mick Barry
Flag of Australia image

if the xml is in same directory as class then try:

document = saxReader.read(getClass().getResourceAsStream("abc.xml"));

if the xml is in same directory as it application is being run from then try

document = saxReader.read(new FileInputStream("abc.xml"));
Avatar of BrijBhasin
BrijBhasin

ASKER

it says saxreader can't be resolved and Cannot make a static reference to the non-static method getClass() from the type Object
whats the rest of your code look like, thats only a snippet in the tutorial
sorry about the sax error .. but i'm still getting the error in my class      

SAXReader reader = new SAXReader();
          //Document document = SAXReader.read(Contract.xml);
            
      Document document = reader.read(getClass().getResourceAsStream("abc.xml"));
            
            List clients = document.selectNodes("//Client");
            List contracts = document.selectNodes("//Contract");

            try {

                  Session session = InitSessionFactory.getInstance().getCurrentSession();
                  Session dom4jSession = session.getSession(EntityMode.DOM4J);
                  Transaction transaction = session.beginTransaction();

                  Iterator iter = clients.iterator();
                  while (iter.hasNext()) {

                        Object next = iter.next();
                        dom4jSession.saveOrUpdate("general.Client", next );

                  }// end while
                  
                  Iterator iter2 = contracts.iterator();
                  while (iter.hasNext()) {

                        Object next = iter2.next();
                        dom4jSession.saveOrUpdate("general.Contract", next );

                  }// end while

                  transaction.commit();
                  session.close();}
            finally{      
                  
            }
replace getClass() with CLASSNAME.class
where CLASSNAME is the name of the class making the call
I'm getting this error for this line.
Document document = reader.read(RunHibernate.class.getResourceAsStream("Contract.xml"));
Unhandled exception type DocumentException
I unable to find an answer to this error online: Unhandled exception type DocumentException

Increasing points .. please help
> RunHibernate.class.getResourceAsStream("Contract.xml")

can you check what value this returns
tried this
      public Document parseUsingSAX() throws DocumentException, Exception
      {
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File("Contract.xml"));
            return document;
      }
RunHibernate R = new RunHibernate();
Document document = R.parseUsingSAX();  // getting Unhandled exception type Exception
where exactly is the file?
The Contract.xml file is the same directory as the RunHibernate.java file
Are you running the application from that directory?
How are you running it?
First I'm trying to build it and Eclipse won't let me do that because of the above error.
try
{
    Document document = R.parseUsingSAX();  // getting Unhandled exception type Exception
}
catch (Exception ex)
{
   ex.printStackTrace();
}
Replaced with above code.
Now I get error on this line
List clients = document.selectNodes("//Client"); // document cannot be resolved
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ok .. I did that and worked through some of the errors in my java code and my hibernate mappin files and now I'm stuck at this error. below the error is my code and the xml file that I'm trying to persist.

----
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select max(CompanyID) from clients
Hibernate: insert into clients (CompanyName, Address1, City, State, Zip, CompanyID) values (?, ?, ?, ?, ?, ?)
org.hibernate.SessionException: Session was already closed
      at org.hibernate.impl.SessionImpl.close(SessionImpl.java:270)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)
      at $Proxy0.close(Unknown Source)
      at RunHibernate.createXMLPersist(RunHibernate.java:134)
      at RunHibernate.main(RunHibernate.java:53)

RunHibernate R = new RunHibernate();

             try
             {
                 Document document = R.parseUsingSAX();  // getting Unhandled exception type Exception
                        List clients = document.selectNodes("//Client");
                        List contracts = document.selectNodes("//Contract");
                        

                              Session session = InitSessionFactory.getInstance().getCurrentSession();
                              Transaction transaction = session.beginTransaction();
                              Session dom4jSession = session.getSession(EntityMode.DOM4J);
                              

                              Iterator iter = clients.iterator();
                              while (iter.hasNext()) {

                                    Object next = iter.next();
                                    dom4jSession.saveOrUpdate("general.clients.Client", next );

                              }// end while
                              
                              Iterator iter2 = contracts.iterator();
                              while (iter.hasNext()) {

                                    Object next = iter2.next();
                                    dom4jSession.saveOrUpdate("general.contracts.Contract", next );
                                    
                              }// end while

                              transaction.commit();
                              session.close();
                              }
                        
             catch (Exception ex)
             {
                ex.printStackTrace();
             }

----------------------------------
<?xml version="1.0"?>
<PontusContract>
      <Client>
      <CompanyName>FICO</CompanyName>
                  <Address1 Type="Main">500 N rd St.</Address1>
                  <City>Minneapolis</City>
                  <State>MN</State>
                  <Zip>55401</Zip>
      </Client>
      <Contract ID="1" ContractType="NDA" CompanyID="2">
      <ContractTitle>XYZ NDA</ContractTitle>
            <ContractDates>
                  <Date Type="ContractSign">1/1/06</Date>
                  <Date Type="ContractExpiry">12/1/06</Date>
            </ContractDates>
            <ClientRefNum>123</ClientRefNum>
            <ContractCustomer>XYZ</ContractCustomer>
      </Contract>
</PontusContract>
so it inserts a client partly but not the contract
>       while (iter.hasNext()) {

In second loop, that should be iter2
ok that fixed the contract not being entered but the "Session was already closed" error remains .. also, these fields are not being populated in the database for some reason.
Address1
AddressType
ContractTitle
>                          session.close();

try removing that line
also, I'm trying to enter this as an xml fragment into  a MySQL field of type text, but when I open editor to see the data it shows up as a bunch of boxes .. so does this mean I can't enter XML in MySQL??
<Date Type="ContractSign">1/1/06</Date>
                  <Date Type="ContractExpiry">12/1/06</Date>
ok the session error went  away but some fields still are not being populated in the database.
check your hibernate mappings are ampping all required fields
I have rechecked my mappings  and they alll map correctly but for some reason it is still not entering these fields. Address1
AddressType
ContractTitle
I can't isolate why it would enter the others and not these even though all the field are setup in the java file and hibernate mappings similarly.
If the data is in the object being save and it is mapped correctly then it should be being wrtten to the database.
Thanks for all your help objects in gettting me close to the solution.. still haven't been able to figure the exact problem though.