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所需的实体类文件夹
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值