jaxb与jpa初应用

首先第一步是读入xml文件中的数据

    package com.cn.tibco;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;



public class ParseXml {
  // private Marshaller marshaller;
     private Unmarshaller unmarshaller;

    
     public ParseXml() {
         try {
             JAXBContext context = JAXBContext.newInstance("com.staffware.frameworks.po");
     //     marshaller = context.createMarshaller();
             unmarshaller = context.createUnmarshaller();    
         
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
       public Object getXml(String filename){
        FileReader fr = null;
        Object o = new Object();
           try {
               fr = new FileReader(new File(filename));
               o = unmarshaller.unmarshal(fr);
            
           } catch (Exception e) {
               e.printStackTrace();
           } finally{
               try {
                   fr.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           return o;
       }



第二步将读到的数据通过jpa持久化到数据库中

package com.cn.tibco;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.staffware.frameworks.po.ManagedEntity;
import com.staffware.frameworks.po.PrimaryKey;

public class DataInsert {
DataInsert(ParseXml px,Object object, String filename){
  EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("com.staffware.frameworks.po");
  EntityManager em = entityManagerFactory.createEntityManager();
  EntityTransaction userTransaction = em.getTransaction();
  userTransaction.begin();
  ParseXml parsexml = px;
  int i = 0;
   while(i<10000){
    Object o = parsexml.getXml(filename);
    object = o;
    PrimaryKey s = ((ManagedEntity) object).getPrimaryKey();
    s.setId(s.toString()+i);
    ((ManagedEntity) object).setPrimaryKey(s);
     em.persist(object);
          i++;
        }
   userTransaction.commit();
   em.close();
   entityManagerFactory.close();
   System.out.println("success");

}
   
}


编写测试类

package com.cn.tibco;

public class Test {

/**
  * @param args
  */
public static void main(String[] args) {
  ParseXml px = new ParseXml();
// String file = "E:\\Tibco\\ipc113\\COM-integration\\Conductor-integration\\src\\data\\order_noful.xml";
  String file1 = "E:\\Tibco\\ipc113\\COM-integration\\Conductor-integration\\src\\data\\plan.xml";
 
  new DataInsert(px,new com.staffware.frameworks.po.ExecutionPlan(),file1);

}

}
附件中附带xml文件和jaxb所需的实体类文件夹





你可能感兴趣的:(JAXB)