精:Berkeley DB XML入门详解

Berkeley DB XML入门
一、Berkeley DB XML安装及使用
http://www.oracle.com/technology/global/cn/products/berkeley-db/xml/index.html下载BerkeleyDB XML的安装文件(dbxml-2.4.16.rar)进行安装。
完装完成后,重启计算机。
使用方法:
1、 通过cmd窗口,输入dbxml即可进入到BerkeleyDB XML的客户端窗口。可执行XQuery语句。
2、 通过JavaAPI来访问BerkeleyDB XML数据库,需要安装目录(Berkeley DB XML 2.4.16\jar)下的三个jar包:db.jar、dbxml.jar、dbxmlexamples.jar

二、java中的应用
代码在附件中:
包括四个类:
DbXmlContainerConfig.java --初始化环境、容器等信息
JAXBUtils.java            --将文档转换成java类
MyDbXmlTest.java          --包括添、删、改、查文档和添索引功能
PhoneBook.java            --文档对应的java类


DbXmlContainerConfig.java --初始化环境、容器等信息:
package com.test.berkeley.service.mytest;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.Environment;
import com.sleepycat.db.EnvironmentConfig;
import com.sleepycat.dbxml.XmlContainer;
import com.sleepycat.dbxml.XmlContainerConfig;
import com.sleepycat.dbxml.XmlException;
import com.sleepycat.dbxml.XmlManager;
import com.sleepycat.dbxml.XmlManagerConfig;

public class DbXmlContainerConfig {
	private Logger log = Logger.getAnonymousLogger();
	private String fileHomePath = "E:/test/dbxml/data";
	
	private static DbXmlContainerConfig dbxmlObj = null;
	private Environment env = null;
	private XmlManager xManager = null;
	private XmlContainer xCont = null;
	private Map<String, XmlContainer> xmlContainerMap;

	/**
	 * 初始化
	 */
	private DbXmlContainerConfig(){
		setEnvironment();
		setXmlManager();
		xmlContainerMap = new HashMap<String, XmlContainer>();
	}
	/**
	 * 获得实例
	 * @return
	 */
	public static DbXmlContainerConfig getInstance(){
		if(dbxmlObj == null){
			dbxmlObj = new DbXmlContainerConfig();
		}
		return dbxmlObj;
	}
	
	/**
	 * 创建Environment对象
	 */
	public void setEnvironment(){
		log.info("创建Environment对象..");
		//创建EnvironmentConfig对象
		EnvironmentConfig envConf = new EnvironmentConfig();
		envConf.setAllowCreate(true); 		//如果设置了true则表示当数据库环境不存在时候重新创建一个数据库环境,默认为false
		envConf.setInitializeCache(true);	//是否打开初始化缓存
        envConf.setInitializeLocking(true); //是否开启锁子系统
		envConf.setInitializeLogging(true);	//是否开启日志子系统
		envConf.setTransactional(true);		//是否使用事务,默认为false
		envConf.setRunRecovery(true);
//      envConf.setThreaded(true);
//      envConf.setLogAutoRemove(true);
		envConf.setMutexIncrement(22);
//      envConf.setLogInMemory(true);
		envConf.setLogRegionSize(1024 * 1024);
//      envConf.setLogBufferSize(30 * 1024 * 1024);
		envConf.setCacheSize(64 * 1024 * 1024);
//		envConf.setLockDetectMode(LockDetectMode.MINWRITE);
		
		//创建Environment对象,并初始化存储位置
		File fileHome = new File(fileHomePath);
		try {
			env = new Environment(fileHome, envConf);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			log.info("文件位置未找到!");
		} catch (DatabaseException e) {
			e.printStackTrace();
			log.info("数据库加载错误");
		}
	}
	
	/**
	 * 创建XmlManager对象
	 */
	public void setXmlManager(){
		System.out.println("setXmlManager......");
        XmlManagerConfig managerConfig = new XmlManagerConfig();
        managerConfig.setAdoptEnvironment(true);
//        managerConfig.setAllowAutoOpen(true);
//        managerConfig.setAllowExternalAccess(true);
        try {
        	xManager = new XmlManager(env, managerConfig);
        } catch (XmlException ex) {
            ex.printStackTrace();
        }
	}
	
	/**
	 * 获得Environment对象
	 * @return
	 */
	public Environment getEnvironment(){
		return env;
	}
	
	/**
	 * 获得XmlManager对象
	 * @return
	 */
	public XmlManager getXmlManager(){
		return xManager;
	}
	
	/**
	 * 获得XmlContainer对象
	 * @param dbxmlName
	 * @return
	 * @throws XmlException
	 */
	public XmlContainer getXmlContainer(String dbxmlName) throws XmlException{
		log.info("获得XmlContainer对象..");
		if (dbxmlName == null || dbxmlName.equals("")) {
            return null;
        }
        if (xmlContainerMap.containsKey(dbxmlName)) {
            return xmlContainerMap.get(dbxmlName);
        }
        XmlContainerConfig xmlContainerConfig = new XmlContainerConfig();
        xmlContainerConfig.setTransactional(true);
        xmlContainerConfig.setAllowCreate(true);
//        xmlContainerConfig.setNodeContainer(false);
        try {
            XmlContainer xmlContainer = xManager.openContainer(dbxmlName, xmlContainerConfig);
            xmlContainerMap.put(dbxmlName, xmlContainer);
            return xmlContainer;
        } catch (XmlException ex) {
            Logger.getLogger(DbXmlContainerConfig.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
	}
}

JAXBUtils.java            --将文档转换成java类
package com.test.berkeley.service.mytest;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

public class JAXBUtils {
	
	public static <T> T convertDocToJava(Class<T> bindClass, String docContent){
		JAXBContext jc;
		Unmarshaller umn;
		InputStreamReader is = null;
		StreamSource ss;
		try {
			jc = JAXBContext.newInstance(bindClass);
			umn = jc.createUnmarshaller();
			is = new InputStreamReader(new ByteArrayInputStream(docContent.getBytes("utf-8")), "utf-8");
			ss = new StreamSource(is);
			JAXBElement<T> book = umn.unmarshal(ss, bindClass);
			return book.getValue();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}


PhoneBook.java            --文档对应的java类
package com.test.berkeley.service.mytest;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PhoneBook", propOrder = {
    "name",
    "phone"
})
/*
<phonebook>
		<name><first>Lisa</first><last>Smith</last></name> 
		<phone type=\"home\">420-992-4801</phone>
		<phone type=\"cell\">390-812-4292</phone>
</phonebook>
*/		
public class PhoneBook {
	@XmlElement(required = true)
	private PhoneBook.Name name;
	private PhoneBook.Phone phone;
	
	@XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "")
	public static class Name {
		@XmlElement(name = "first", required = true)
		private String first;
		@XmlElement(name = "last", required = true)
		private String last;
		public String getFirst() {
			return first;
		}
		public void setFirst(String first) {
			this.first = first;
		}
		public String getLast() {
			return last;
		}
		public void setLast(String last) {
			this.last = last;
		}
		
	}
	
	@XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "")
	public static class Phone {
		@XmlAttribute(name = "type", required = true)
		private String type;

		public String getType() {
			return type;
		}

		public void setType(String type) {
			this.type = type;
		}
		
	}

	public PhoneBook.Name getName() {
		return name;
	}

	public void setName(PhoneBook.Name name) {
		this.name = name;
	}

	public PhoneBook.Phone getPhone() {
		return phone;
	}

	public void setPhone(PhoneBook.Phone phone) {
		this.phone = phone;
	}
}



MyDbXmlTest.java          --包括添、删、改、查文档和添索引功能
package com.test.berkeley.service.mytest;

import com.sleepycat.dbxml.XmlContainer;
import com.sleepycat.dbxml.XmlDocument;
import com.sleepycat.dbxml.XmlException;
import com.sleepycat.dbxml.XmlIndexLookup;
import com.sleepycat.dbxml.XmlIndexSpecification;
import com.sleepycat.dbxml.XmlManager;
import com.sleepycat.dbxml.XmlQueryContext;
import com.sleepycat.dbxml.XmlQueryExpression;
import com.sleepycat.dbxml.XmlResults;
import com.sleepycat.dbxml.XmlTransaction;
import com.sleepycat.dbxml.XmlUpdateContext;
import com.sleepycat.dbxml.XmlValue;

public class MyDbXmlTest {
	protected DbXmlContainerConfig dbxmlConf =  null;
	
	
	private String dbxmlName = "phone.dbxml";
	static final private String m_StrName1 = "phone1";
	static final private String m_StrXml1 = "<PhoneBook><name><first>Tom</first><last>Jones</last></name><phone type=\"home\">420-203-2033</phone></PhoneBook>";
	static final private String m_StrName2 = "phone2";
	static final private String m_StrXml2 = "<PhoneBook><name><first>Lisa</first><last>Smith</last></name> <phone type=\"home\">420-992-4801</phone><phone type=\"cell\">390-812-4292</phone></PhoneBook>";
	static final private String m_StrName3 = "phone3";
	static final private String m_StrXml3 = "<PhoneBook><name><first>Tom</first><last>Jones</last></name><phone type=\"home\">420-203-2033</phone></PhoneBook>";
	
	static final private String m_strquery = "collection('phone.dbxml')/phonebook";
	static final private String m_strquery1 = "collection('phone.dbxml')/phonebook[name/first=$name]";
	
	public MyDbXmlTest(){
		dbxmlConf = DbXmlContainerConfig.getInstance();
	}
	
	public static void main(String[] args){
		MyDbXmlTest myDb = new MyDbXmlTest();
		try {
			/*添加文档*/
//			myDb.addDoc(m_StrName1, m_StrXml1);
//			myDb.addDoc(m_StrName2, m_StrXml2);
			/*修改文档*/
//			myDb.updateDoc(m_StrName1, m_StrXml2);
			/*查询文档*/
			myDb.queryXmlData(m_strquery);
			if(myDb.getDocByKey(m_StrName3) == null){
				myDb.addDoc(m_StrName3, m_StrXml3);
			}else{
				System.out.println("Tom 已经存在!");
				//删除文档
//				myDb.deleteDoc(m_StrName3);
			}
			
		} catch (XmlException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 保存文档
	 * @throws XmlException 
	 */
	public void addDoc(String docName, String docStr) throws XmlException{
		XmlManager x_mng = dbxmlConf.getXmlManager();
		XmlContainer x_cont = dbxmlConf.getXmlContainer(dbxmlName);
		//创建事务
		XmlTransaction x_tran = x_mng.createTransaction();
		XmlUpdateContext x_updateCon = x_mng.createUpdateContext();
		x_cont.putDocument(x_tran, docName, docStr, x_updateCon);
		x_tran.commit();
	}
	
	/**
	 * 更新文档
	 * @param docName
	 * @param docStr
	 * @throws XmlException
	 */
	public void updateDoc(String docName, String docStr) throws XmlException{
		XmlManager x_mng = dbxmlConf.getXmlManager();
		XmlUpdateContext m_uc = x_mng.createUpdateContext();
		XmlContainer x_cont = dbxmlConf.getXmlContainer(dbxmlName);
		//创建事务
		XmlTransaction x_tran = x_mng.createTransaction();
		XmlDocument doc = x_cont.getDocument(x_tran, docName);
		doc.setContent(docStr);
		x_cont.updateDocument(x_tran, doc);
		x_tran.commit();
//		x_cont.deleteDocument(docName, m_uc);
//		x_cont.putDocument(docName, docStr, m_uc);
	}
	
	/**
	 * 删除文档
	 * @param docName
	 * @throws XmlException
	 */
	public void deleteDoc(String docName) throws XmlException{
		XmlManager x_mng = dbxmlConf.getXmlManager();
		//创建事务
		XmlTransaction x_tran = x_mng.createTransaction();
		XmlUpdateContext m_uc = x_mng.createUpdateContext();
		XmlContainer x_cont = dbxmlConf.getXmlContainer(dbxmlName);
		x_cont.deleteDocument(x_tran, docName, m_uc);
		x_tran.commit();
		System.out.println("已经删除!");
	}

	/**
	 * 查询数据,使用xquery
	 * @param strQuery
	 * @throws XmlException
	 */
	public void queryXmlData(String strQuery) throws XmlException {
		XmlManager x_mng = dbxmlConf.getXmlManager();
		XmlContainer x_cont = dbxmlConf.getXmlContainer(dbxmlName);
		//创建事务
		XmlTransaction x_tran = x_mng.createTransaction();
		XmlQueryContext m_qc = x_mng.createQueryContext();
		XmlQueryExpression expr = x_mng.prepare(x_tran, strQuery, m_qc);
	    XmlResults res = expr.execute(m_qc);
		x_tran.commit();
		
	    XmlValue value = new XmlValue();
	    /*System.out.print("Result: ");
	    while ((value = res.next()) != null) {
	    	System.out.println("\t" + value.asString());
	    	value.delete();
	    }*/
	    
	    //把查询结果对应对象
	    while ((value = res.next()) != null) {
	    	String tempStr = value.asString();
	    	if (tempStr != null && !tempStr.equals("")) {
	    		PhoneBook objData = JAXBUtils.convertDocToJava(PhoneBook.class, tempStr);
	    		System.out.println("name=" + objData.getName().getFirst() + "+" + objData.getName().getLast());
	    		if(objData.getPhone() != null){
	    			System.out.println("phone=" + objData.getPhone().getType());
	    		}
            }
	    	value.delete();
	    }
	    expr.delete();
	}
	/**
	 * 判断名称是否存在
	 * @param name
	 * @return
	 * @throws XmlException
	 */
	public boolean isEmpty(String name) throws XmlException{
		XmlManager x_mng = dbxmlConf.getXmlManager();
		//创建事务
		XmlTransaction x_tran = x_mng.createTransaction();
		XmlQueryContext m_qc = x_mng.createQueryContext();
		m_qc.setVariableValue("name", new XmlValue(name));
		XmlQueryExpression xqe = x_mng.prepare(x_tran, m_strquery1, m_qc);
		XmlResults rs = xqe.execute(m_qc);
		if(rs.size() > 0){
			return false;
		}
		return true;
	}
	/**
	 * 根据文档名称查找文档
	 * @param key
	 * @return
	 * @throws XmlException
	 */
	public String getDocByKey(String key) throws XmlException{
		XmlManager x_mng = dbxmlConf.getXmlManager();
		//创建事务
		XmlTransaction x_tran = x_mng.createTransaction();
		XmlContainer x_cont = dbxmlConf.getXmlContainer(dbxmlName);
		XmlDocument doc = null;
		try{
			doc = x_cont.getDocument(x_tran, key);
		}catch(XmlException ex){
			if(ex.getErrorCode() == XmlException.DOCUMENT_NOT_FOUND){
				x_tran.abort();
				return null;
			}
		}
		x_tran.commit();
		String str = doc.getContentAsString();
		if(doc != null && doc.getContent() != null){
			return doc.getContentAsString();
		}
		return null;
	}
	
	/**
	 * 添加索引
	 * @throws XmlException
	 */
	public void AddIndex() throws XmlException{
		XmlManager x_mng = dbxmlConf.getXmlManager();
		//创建事务
		XmlTransaction x_tran = x_mng.createTransaction();
		XmlUpdateContext m_uc = x_mng.createUpdateContext();
		XmlContainer x_cont = dbxmlConf.getXmlContainer(dbxmlName);
		XmlIndexSpecification ins = x_cont.getIndexSpecification(x_tran);
		//[unique]-{path type}-{node type}-{key type}-{syntax type}
		ins.addIndex("", "firstName", "node-element-substring-string");
//		ins.addIndex("", "PRICE", "node-element-equality-double");
		//更新索引到容器中
		XmlUpdateContext xuc = x_mng.createUpdateContext();
		x_cont.setIndexSpecification(x_tran, ins, xuc);
		x_tran.commit();
	}
	
}

如果朋友们觉得这篇文章对您有用,而且您需要茶叶茶具和零食之类的东东,请大家到下面这家店铺购买“品润茶业”,做批发的,价格超便宜,希望大家多多支持!
地址:http://prtea.taobao.com
请转载的朋友,把以上文字也带上,珍惜别人的劳动果实,谢谢!

你可能感兴趣的:(java,oracle,xml)