?
Solved

Hibernate XMl persistence

Posted on 2006-05-01
28
Medium Priority
?
483 Views
Last Modified: 2008-01-09
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);
0
Comment
Question by:BrijBhasin
  • 15
  • 12
27 Comments
 
LVL 92

Expert Comment

by:objects
ID: 16581821
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"));
0
 

Author Comment

by:BrijBhasin
ID: 16581875
it says saxreader can't be resolved and Cannot make a static reference to the non-static method getClass() from the type Object
0
 
LVL 92

Expert Comment

by:objects
ID: 16581882
whats the rest of your code look like, thats only a snippet in the tutorial
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:BrijBhasin
ID: 16581917
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{      
                  
            }
0
 
LVL 92

Expert Comment

by:objects
ID: 16581983
replace getClass() with CLASSNAME.class
where CLASSNAME is the name of the class making the call
0
 

Author Comment

by:BrijBhasin
ID: 16586378
I'm getting this error for this line.
Document document = reader.read(RunHibernate.class.getResourceAsStream("Contract.xml"));
Unhandled exception type DocumentException
0
 

Author Comment

by:BrijBhasin
ID: 16591153
I unable to find an answer to this error online: Unhandled exception type DocumentException

Increasing points .. please help
0
 
LVL 92

Expert Comment

by:objects
ID: 16591216
> RunHibernate.class.getResourceAsStream("Contract.xml")

can you check what value this returns
0
 

Author Comment

by:BrijBhasin
ID: 16591229
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
0
 
LVL 92

Expert Comment

by:objects
ID: 16591324
where exactly is the file?
0
 

Author Comment

by:BrijBhasin
ID: 16591774
The Contract.xml file is the same directory as the RunHibernate.java file
0
 
LVL 92

Expert Comment

by:objects
ID: 16594375
Are you running the application from that directory?
How are you running it?
0
 

Author Comment

by:BrijBhasin
ID: 16596654
First I'm trying to build it and Eclipse won't let me do that because of the above error.
0
 
LVL 92

Expert Comment

by:objects
ID: 16601180
try
{
    Document document = R.parseUsingSAX();  // getting Unhandled exception type Exception
}
catch (Exception ex)
{
   ex.printStackTrace();
}
0
 

Author Comment

by:BrijBhasin
ID: 16601309
Replaced with above code.
Now I get error on this line
List clients = document.selectNodes("//Client"); // document cannot be resolved
0
 
LVL 92

Accepted Solution

by:
objects earned 1500 total points
ID: 16601321
move it inside the try/catch
0
 

Author Comment

by:BrijBhasin
ID: 16601563
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>
0
 

Author Comment

by:BrijBhasin
ID: 16601566
so it inserts a client partly but not the contract
0
 
LVL 92

Expert Comment

by:objects
ID: 16601585
>       while (iter.hasNext()) {

In second loop, that should be iter2
0
 

Author Comment

by:BrijBhasin
ID: 16601641
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
0
 
LVL 92

Expert Comment

by:objects
ID: 16601656
>                          session.close();

try removing that line
0
 

Author Comment

by:BrijBhasin
ID: 16601660
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>
0
 

Author Comment

by:BrijBhasin
ID: 16601665
ok the session error went  away but some fields still are not being populated in the database.
0
 
LVL 92

Expert Comment

by:objects
ID: 16601718
check your hibernate mappings are ampping all required fields
0
 

Author Comment

by:BrijBhasin
ID: 16606440
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.
0
 
LVL 92

Expert Comment

by:objects
ID: 16610611
If the data is in the object being save and it is mapped correctly then it should be being wrtten to the database.
0
 

Author Comment

by:BrijBhasin
ID: 16854505
Thanks for all your help objects in gettting me close to the solution.. still haven't been able to figure the exact problem though.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month14 days, 15 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question